[0-9]+(?:\.[0-9]+)*+) # release segment
(?P # pre-release
[._-]?+
(?Palpha|a|beta|b|preview|pre|c|rc)
[._-]?+
(?P[0-9]+)?
)?+
(?P # post release
(?:-(?P[0-9]+))
|
(?:
[._-]?
(?Ppost|rev|r)
[._-]?
(?P[0-9]+)?
)
)?+
(?P # dev release
[._-]?+
(?Pdev)
[._-]?+
(?P[0-9]+)?
)?+
)
(?:\+
(?P # local version
[a-z0-9]+
(?:[._-][a-z0-9]+)*+
)
)?+
"""
_VERSION_PATTERN_OLD = _VERSION_PATTERN.replace("*+", "*").replace("?+", "?")
# Possessive qualifiers were added in Python 3.11.
# CPython 3.11.0-3.11.4 had a bug: https://github.com/python/cpython/pull/107795
# Older PyPy also had a bug.
VERSION_PATTERN = (
_VERSION_PATTERN_OLD
if (sys.implementation.name == "cpython" and sys.version_info < (3, 11, 5))
or (sys.implementation.name == "pypy" and sys.version_info < (3, 11, 13))
or sys.version_info < (3, 11)
else _VERSION_PATTERN
)
"""
A string containing the regular expression used to match a valid version.
The pattern is not anchored at either end, and is intended for embedding in larger
expressions (for example, matching a version number as part of a file name). The
regular expression should be compiled with the ``re.VERBOSE`` and ``re.IGNORECASE``
flags set.
:meta hide-value:
"""
# Validation pattern for local version in replace()
_LOCAL_PATTERN = re.compile(r"[a-z0-9]+(?:[._-][a-z0-9]+)*", re.IGNORECASE)
def _validate_epoch(value: object, /) -> int:
epoch = value or 0
if isinstance(epoch, int) and epoch >= 0:
return epoch
msg = f"epoch must be non-negative integer, got {epoch}"
raise InvalidVersion(msg)
def _validate_release(value: object, /) -> tuple[int, ...]:
release = (0,) if value is None else value
if (
isinstance(release, tuple)
and len(release) > 0
and all(isinstance(i, int) and i >= 0 for i in release)
):
return release
msg = f"release must be a non-empty tuple of non-negative integers, got {release}"
raise InvalidVersion(msg)
def _validate_pre(value: object, /) -> tuple[Literal["a", "b", "rc"], int] | None:
if value is None:
return value
if (
isinstance(value, tuple)
and len(value) == 2
and value[0] in ("a", "b", "rc")
and isinstance(value[1], int)
and value[1] >= 0
):
return value
msg = f"pre must be a tuple of ('a'|'b'|'rc', non-negative int), got {value}"
raise InvalidVersion(msg)
def _validate_post(value: object, /) -> tuple[Literal["post"], int] | None:
if value is None:
return value
if isinstance(value, int) and value >= 0:
return ("post", value)
msg = f"post must be non-negative integer, got {value}"
raise InvalidVersion(msg)
def _validate_dev(value: object, /) -> tuple[Literal["dev"], int] | None:
if value is None:
return value
if isinstance(value, int) and value >= 0:
return ("dev", value)
msg = f"dev must be non-negative integer, got {value}"
raise InvalidVersion(msg)
def _validate_local(value: object, /) -> LocalType | None:
if value is None:
return value
if isinstance(value, str) and _LOCAL_PATTERN.fullmatch(value):
return _parse_local_version(value)
msg = f"local must be a valid version string, got {value!r}"
raise InvalidVersion(msg)
# Backward compatibility for internals before 26.0. Do not use.
class _Version(NamedTuple):
epoch: int
release: tuple[int, ...]
dev: tuple[str, int] | None
pre: tuple[str, int] | None
post: tuple[str, int] | None
local: LocalType | None
class Version(_BaseVersion):
"""This class abstracts handling of a project's versions.
A :class:`Version` instance is comparison aware and can be compared and
sorted using the standard Python interfaces.
>>> v1 = Version("1.0a5")
>>> v2 = Version("1.0")
>>> v1
>>> v2
>>> v1 < v2
True
>>> v1 == v2
False
>>> v1 > v2
False
>>> v1 >= v2
False
>>> v1 <= v2
True
"""
__slots__ = ("_dev", "_epoch", "_key_cache", "_local", "_post", "_pre", "_release")
__match_args__ = ("_str",)
_regex = re.compile(r"\s*" + VERSION_PATTERN + r"\s*", re.VERBOSE | re.IGNORECASE)
_epoch: int
_release: tuple[int, ...]
_dev: tuple[str, int] | None
_pre: tuple[str, int] | None
_post: tuple[str, int] | None
_local: LocalType | None
_key_cache: CmpKey | None
def __init__(self, version: str) -> None:
"""Initialize a Version object.
:param version:
The string representation of a version which will be parsed and normalized
before use.
:raises InvalidVersion:
If the ``version`` does not conform to PEP 440 in any way then this
exception will be raised.
"""
# Validate the version and parse it into pieces
match = self._regex.fullmatch(version)
if not match:
raise InvalidVersion(f"Invalid version: {version!r}")
self._epoch = int(match.group("epoch")) if match.group("epoch") else 0
self._release = tuple(map(int, match.group("release").split(".")))
self._pre = _parse_letter_version(match.group("pre_l"), match.group("pre_n"))
self._post = _parse_letter_version(
match.group("post_l"), match.group("post_n1") or match.group("post_n2")
)
self._dev = _parse_letter_version(match.group("dev_l"), match.group("dev_n"))
self._local = _parse_local_version(match.group("local"))
# Key which will be used for sorting
self._key_cache = None
def __replace__(self, **kwargs: Unpack[_VersionReplace]) -> Self:
epoch = _validate_epoch(kwargs["epoch"]) if "epoch" in kwargs else self._epoch
release = (
_validate_release(kwargs["release"])
if "release" in kwargs
else self._release
)
pre = _validate_pre(kwargs["pre"]) if "pre" in kwargs else self._pre
post = _validate_post(kwargs["post"]) if "post" in kwargs else self._post
dev = _validate_dev(kwargs["dev"]) if "dev" in kwargs else self._dev
local = _validate_local(kwargs["local"]) if "local" in kwargs else self._local
if (
epoch == self._epoch
and release == self._release
and pre == self._pre
and post == self._post
and dev == self._dev
and local == self._local
):
return self
new_version = self.__class__.__new__(self.__class__)
new_version._key_cache = None
new_version._epoch = epoch
new_version._release = release
new_version._pre = pre
new_version._post = post
new_version._dev = dev
new_version._local = local
return new_version
@property
def _key(self) -> CmpKey:
if self._key_cache is None:
self._key_cache = _cmpkey(
self._epoch,
self._release,
self._pre,
self._post,
self._dev,
self._local,
)
return self._key_cache
@property
@_deprecated("Version._version is private and will be removed soon")
def _version(self) -> _Version:
return _Version(
self._epoch, self._release, self._dev, self._pre, self._post, self._local
)
@_version.setter
@_deprecated("Version._version is private and will be removed soon")
def _version(self, value: _Version) -> None:
self._epoch = value.epoch
self._release = value.release
self._dev = value.dev
self._pre = value.pre
self._post = value.post
self._local = value.local
self._key_cache = None
def __repr__(self) -> str:
"""A representation of the Version that shows all internal state.
>>> Version('1.0.0')
"""
return f""
def __str__(self) -> str:
"""A string representation of the version that can be round-tripped.
>>> str(Version("1.0a5"))
'1.0a5'
"""
# This is a hot function, so not calling self.base_version
version = ".".join(map(str, self.release))
# Epoch
if self.epoch:
version = f"{self.epoch}!{version}"
# Pre-release
if self.pre is not None:
version += "".join(map(str, self.pre))
# Post-release
if self.post is not None:
version += f".post{self.post}"
# Development release
if self.dev is not None:
version += f".dev{self.dev}"
# Local version segment
if self.local is not None:
version += f"+{self.local}"
return version
@property
def _str(self) -> str:
"""Internal property for match_args"""
return str(self)
@property
def epoch(self) -> int:
"""The epoch of the version.
>>> Version("2.0.0").epoch
0
>>> Version("1!2.0.0").epoch
1
"""
return self._epoch
@property
def release(self) -> tuple[int, ...]:
"""The components of the "release" segment of the version.
>>> Version("1.2.3").release
(1, 2, 3)
>>> Version("2.0.0").release
(2, 0, 0)
>>> Version("1!2.0.0.post0").release
(2, 0, 0)
Includes trailing zeroes but not the epoch or any pre-release / development /
post-release suffixes.
"""
return self._release
@property
def pre(self) -> tuple[str, int] | None:
"""The pre-release segment of the version.
>>> print(Version("1.2.3").pre)
None
>>> Version("1.2.3a1").pre
('a', 1)
>>> Version("1.2.3b1").pre
('b', 1)
>>> Version("1.2.3rc1").pre
('rc', 1)
"""
return self._pre
@property
def post(self) -> int | None:
"""The post-release number of the version.
>>> print(Version("1.2.3").post)
None
>>> Version("1.2.3.post1").post
1
"""
return self._post[1] if self._post else None
@property
def dev(self) -> int | None:
"""The development number of the version.
>>> print(Version("1.2.3").dev)
None
>>> Version("1.2.3.dev1").dev
1
"""
return self._dev[1] if self._dev else None
@property
def local(self) -> str | None:
"""The local version segment of the version.
>>> print(Version("1.2.3").local)
None
>>> Version("1.2.3+abc").local
'abc'
"""
if self._local:
return ".".join(str(x) for x in self._local)
else:
return None
@property
def public(self) -> str:
"""The public portion of the version.
>>> Version("1.2.3").public
'1.2.3'
>>> Version("1.2.3+abc").public
'1.2.3'
>>> Version("1!1.2.3dev1+abc").public
'1!1.2.3.dev1'
"""
return str(self).split("+", 1)[0]
@property
def base_version(self) -> str:
"""The "base version" of the version.
>>> Version("1.2.3").base_version
'1.2.3'
>>> Version("1.2.3+abc").base_version
'1.2.3'
>>> Version("1!1.2.3dev1+abc").base_version
'1!1.2.3'
The "base version" is the public version of the project without any pre or post
release markers.
"""
release_segment = ".".join(map(str, self.release))
return f"{self.epoch}!{release_segment}" if self.epoch else release_segment
@property
def is_prerelease(self) -> bool:
"""Whether this version is a pre-release.
>>> Version("1.2.3").is_prerelease
False
>>> Version("1.2.3a1").is_prerelease
True
>>> Version("1.2.3b1").is_prerelease
True
>>> Version("1.2.3rc1").is_prerelease
True
>>> Version("1.2.3dev1").is_prerelease
True
"""
return self.dev is not None or self.pre is not None
@property
def is_postrelease(self) -> bool:
"""Whether this version is a post-release.
>>> Version("1.2.3").is_postrelease
False
>>> Version("1.2.3.post1").is_postrelease
True
"""
return self.post is not None
@property
def is_devrelease(self) -> bool:
"""Whether this version is a development release.
>>> Version("1.2.3").is_devrelease
False
>>> Version("1.2.3.dev1").is_devrelease
True
"""
return self.dev is not None
@property
def major(self) -> int:
"""The first item of :attr:`release` or ``0`` if unavailable.
>>> Version("1.2.3").major
1
"""
return self.release[0] if len(self.release) >= 1 else 0
@property
def minor(self) -> int:
"""The second item of :attr:`release` or ``0`` if unavailable.
>>> Version("1.2.3").minor
2
>>> Version("1").minor
0
"""
return self.release[1] if len(self.release) >= 2 else 0
@property
def micro(self) -> int:
"""The third item of :attr:`release` or ``0`` if unavailable.
>>> Version("1.2.3").micro
3
>>> Version("1").micro
0
"""
return self.release[2] if len(self.release) >= 3 else 0
class _TrimmedRelease(Version):
__slots__ = ()
def __init__(self, version: str | Version) -> None:
if isinstance(version, Version):
self._epoch = version._epoch
self._release = version._release
self._dev = version._dev
self._pre = version._pre
self._post = version._post
self._local = version._local
self._key_cache = version._key_cache
return
super().__init__(version) # pragma: no cover
@property
def release(self) -> tuple[int, ...]:
"""
Release segment without any trailing zeros.
>>> _TrimmedRelease('1.0.0').release
(1,)
>>> _TrimmedRelease('0.0').release
(0,)
"""
# This leaves one 0.
rel = super().release
len_release = len(rel)
i = len_release
while i > 1 and rel[i - 1] == 0:
i -= 1
return rel if i == len_release else rel[:i]
def _parse_letter_version(
letter: str | None, number: str | bytes | SupportsInt | None
) -> tuple[str, int] | None:
if letter:
# We normalize any letters to their lower case form
letter = letter.lower()
# We consider some words to be alternate spellings of other words and
# in those cases we want to normalize the spellings to our preferred
# spelling.
letter = _LETTER_NORMALIZATION.get(letter, letter)
# We consider there to be an implicit 0 in a pre-release if there is
# not a numeral associated with it.
return letter, int(number or 0)
if number:
# We assume if we are given a number, but we are not given a letter
# then this is using the implicit post release syntax (e.g. 1.0-1)
return "post", int(number)
return None
_local_version_separators = re.compile(r"[\._-]")
def _parse_local_version(local: str | None) -> LocalType | None:
"""
Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
"""
if local is not None:
return tuple(
part.lower() if not part.isdigit() else int(part)
for part in _local_version_separators.split(local)
)
return None
def _cmpkey(
epoch: int,
release: tuple[int, ...],
pre: tuple[str, int] | None,
post: tuple[str, int] | None,
dev: tuple[str, int] | None,
local: LocalType | None,
) -> CmpKey:
# When we compare a release version, we want to compare it with all of the
# trailing zeros removed. We will use this for our sorting key.
len_release = len(release)
i = len_release
while i and release[i - 1] == 0:
i -= 1
_release = release if i == len_release else release[:i]
# We need to "trick" the sorting algorithm to put 1.0.dev0 before 1.0a0.
# We'll do this by abusing the pre segment, but we _only_ want to do this
# if there is not a pre or a post segment. If we have one of those then
# the normal sorting rules will handle this case correctly.
if pre is None and post is None and dev is not None:
_pre: CmpPrePostDevType = NegativeInfinity
# Versions without a pre-release (except as noted above) should sort after
# those with one.
elif pre is None:
_pre = Infinity
else:
_pre = pre
# Versions without a post segment should sort before those with one.
if post is None:
_post: CmpPrePostDevType = NegativeInfinity
else:
_post = post
# Versions without a development segment should sort after those with one.
if dev is None:
_dev: CmpPrePostDevType = Infinity
else:
_dev = dev
if local is None:
# Versions without a local segment should sort before those with one.
_local: CmpLocalType = NegativeInfinity
else:
# Versions with a local segment need that segment parsed to implement
# the sorting rules in PEP440.
# - Alpha numeric segments sort before numeric segments
# - Alpha numeric segments sort lexicographically
# - Numeric segments sort numerically
# - Shorter versions sort before longer versions when the prefixes
# match exactly
_local = tuple(
(i, "") if isinstance(i, int) else (NegativeInfinity, i) for i in local
)
return epoch, _release, _pre, _post, _dev, _local
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1768936045.8183684
packaging-26.0/tests/__init__.py 0000644 0000000 0000000 00000000264 15133751156 013577 0 ustar 00 # This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1768936045.8183684
packaging-26.0/tests/manylinux/build.sh 0000755 0000000 0000000 00000003402 15133751156 015145 0 ustar 00 #!/bin/bash
set -x
set -e
if [ $# -eq 0 ]; then
docker run --rm -v $(pwd):/home/hello-world arm32v5/debian /home/hello-world/manylinux/build.sh incontainer 52
docker run --rm -v $(pwd):/home/hello-world arm32v7/debian /home/hello-world/manylinux/build.sh incontainer 52
docker run --rm -v $(pwd):/home/hello-world i386/debian /home/hello-world/manylinux/build.sh incontainer 52
docker run --rm -v $(pwd):/home/hello-world s390x/debian /home/hello-world/manylinux/build.sh incontainer 64
docker run --rm -v $(pwd):/home/hello-world debian /home/hello-world/manylinux/build.sh incontainer 64
docker run --rm -v $(pwd):/home/hello-world debian /home/hello-world/manylinux/build.sh x32 52
cp -f manylinux/hello-world-x86_64-i386 manylinux/hello-world-invalid-magic
printf "\x00" | dd of=manylinux/hello-world-invalid-magic bs=1 seek=0x00 count=1 conv=notrunc
cp -f manylinux/hello-world-x86_64-i386 manylinux/hello-world-invalid-class
printf "\x00" | dd of=manylinux/hello-world-invalid-class bs=1 seek=0x04 count=1 conv=notrunc
cp -f manylinux/hello-world-x86_64-i386 manylinux/hello-world-invalid-data
printf "\x00" | dd of=manylinux/hello-world-invalid-data bs=1 seek=0x05 count=1 conv=notrunc
head -c 40 manylinux/hello-world-x86_64-i386 > manylinux/hello-world-too-short
exit 0
fi
export DEBIAN_FRONTEND=noninteractive
cd /home/hello-world/
apt-get update
apt-get install -y --no-install-recommends gcc libc6-dev
if [ "$1" == "incontainer" ]; then
ARCH=$(dpkg --print-architecture)
CFLAGS=""
else
ARCH=$1
dpkg --add-architecture ${ARCH}
apt-get install -y --no-install-recommends gcc-multilib libc6-dev-${ARCH}
CFLAGS="-mx32"
fi
NAME=hello-world-$(uname -m)-${ARCH}
gcc -Os -s ${CFLAGS} -o ${NAME}-full hello-world.c
head -c $2 ${NAME}-full > ${NAME}
rm -f ${NAME}-full
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1768936045.8183684
packaging-26.0/tests/manylinux/hello-world-armv7l-armel 0000755 0000000 0000000 00000000064 15133751156 020172 0 ustar 00 ELF ( 4 4 ( ././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1768936045.8183684
packaging-26.0/tests/manylinux/hello-world-armv7l-armhf 0000755 0000000 0000000 00000000064 15133751156 020167 0 ustar 00 ELF ( 4 4 ( ././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1768936045.8183684
packaging-26.0/tests/manylinux/hello-world-invalid-class 0000755 0000000 0000000 00000000064 15133751156 020415 0 ustar 00 ELF 4 01 4 ( ././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1768936045.8183684
packaging-26.0/tests/manylinux/hello-world-invalid-data 0000755 0000000 0000000 00000000064 15133751156 020221 0 ustar 00 ELF 4 01 4 ( ././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1768936045.8183684
packaging-26.0/tests/manylinux/hello-world-invalid-magic 0000755 0000000 0000000 00000000064 15133751156 020370 0 ustar 00 ELF 4 01 4 ( ././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1768936045.8183684
packaging-26.0/tests/manylinux/hello-world-s390x-s390x 0000644 0000000 0000000 00000000100 15133751156 017422 0 ustar 00 ELF P @ p @ 8 @ ././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1768936045.8183684
packaging-26.0/tests/manylinux/hello-world-too-short 0000644 0000000 0000000 00000000050 15133751156 017612 0 ustar 00 ELF 4 01 ././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1768936045.8183684
packaging-26.0/tests/manylinux/hello-world-x86_64-amd64 0000644 0000000 0000000 00000000100 15133751156 017517 0 ustar 00 ELF > p @ H1 @ 8 @ ././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1768936045.8183684
packaging-26.0/tests/manylinux/hello-world-x86_64-i386 0000755 0000000 0000000 00000000064 15133751156 017311 0 ustar 00 ELF 4 01 4 ( ././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1768936045.8183684
packaging-26.0/tests/manylinux/hello-world-x86_64-x32 0000755 0000000 0000000 00000000064 15133751156 017234 0 ustar 00 ELF > p 4 <1 4 ( ././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1768936045.8183684
packaging-26.0/tests/metadata/everything.metadata 0000644 0000000 0000000 00000003471 15133751156 017137 0 ustar 00 Metadata-Version: 2.5
Name: BeagleVote
Version: 1.0a2
Platform: ObscureUnix
Platform: RareDOS
Supported-Platform: RedHat 7.2
Supported-Platform: i386-win32-2791
Summary: A module for collecting votes from beagles.
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Keywords: dog,puppy,voting,election
Home-page: http://www.example.com/~cschultz/bvote/
Download-URL: …/BeagleVote-0.45.tgz
Author: C. Schultz, Universal Features Syndicate,
Los Angeles, CA
Author-email: "C. Schultz"
Maintainer: C. Schultz, Universal Features Syndicate,
Los Angeles, CA
Maintainer-email: "C. Schultz"
License: This software may only be obtained by sending the
author a postcard, and then the user promises not
to redistribute it.
License-Expression: Apache-2.0 OR BSD-2-Clause
License-File: LICENSE.APACHE
License-File: LICENSE.BSD
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console (Text Based)
Provides-Extra: pdf
Requires-Dist: reportlab; extra == 'pdf'
Requires-Dist: pkginfo
Requires-Dist: PasteDeploy
Requires-Dist: zope.interface (>3.5.0)
Requires-Dist: pywin32 >1.0; sys_platform == 'win32'
Requires-Python: >=3
Requires-External: C
Requires-External: libpng (>=1.5)
Requires-External: make; sys_platform != "win32"
Project-URL: Bug Tracker, http://bitbucket.org/tarek/distribute/issues/
Project-URL: Documentation, https://example.com/BeagleVote
Provides-Dist: OtherProject
Provides-Dist: AnotherProject (3.4)
Provides-Dist: virtual_package; python_version >= "3.4"
Dynamic: Obsoletes-Dist
Import-Name: beaglevote
Import-Name: _beaglevote ; private
Import-Namespace: spam
Import-Namespace: _bacon ; private
ThisIsNotReal: Hello!
This description intentionally left blank.
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1768936045.8183684
packaging-26.0/tests/musllinux/glibc-x86_64 0000755 0000000 0000000 00000002000 15133751156 015456 0 ustar 00 ELF > @ 9 @ 8
@ @ @ @ X X - = = X ` - = = 8 8 8 X X X D D Std 8 8 8 Ptd D D Qtd Rtd - = = H H /lib64/ld-linux-x86-64.so.2 GNU GNU KWz7Styxyʍ GNU em Q ' ././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1768936045.8183684
packaging-26.0/tests/musllinux/musl-aarch64 0000755 0000000 0000000 00000002000 15133751156 015650 0 ustar 00 ELF @ @ # @ 8 @ @ @ @
`
Ptd 4 4 Qtd Rtd
X X /lib/ld-musl-aarch64.so.1
@
" L d ~ #
_init printf _fini __cxa_finalize __libc_start_main libc.musl-aarch64.so.1 __deregister_frame_info _ITM_registerTMCloneTable _ITM_deregisterTMCloneTabl././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1768936045.8183684
packaging-26.0/tests/musllinux/musl-i386 0000755 0000000 0000000 00000002000 15133751156 015111 0 ustar 00 ELF 4 = 4
( ! 4 4 4 @ @ t t t ` ` . > > ( / ? ? Ptd $ $ Qtd Rtd. > > /lib/ld-musl-i386.so.1 $ " H d ~ # _init printf _fini __cxa_finalize __libc_start_main libc.musl-x86.so.1 __register_frame_info_bases _ITM_registerTMCloneTable __deregister_frame_info_bases _ITM_deregisterTMCloneTable ? ? ? @ ? ? ? ? ? ? ? ././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1768936045.8183684
packaging-26.0/tests/musllinux/musl-x86_64 0000755 0000000 0000000 00000002000 15133751156 015356 0 ustar 00 ELF > s @ A @ 8
@ ! @ @ @ 0 0 p p p Y Y . > > ` 0. 0> 0> Ptd $ $ Qtd Rtd . > > /lib/ld-musl-x86_64.so.1 @ em K c } # " Q _init printf _fini __cxa_finalize __libc_start_main libc.musl-x86_64.so.1 __der././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1768936045.8193686
packaging-26.0/tests/pylock/pylock.spec-example.toml 0000644 0000000 0000000 00000005322 15133751156 017547 0 ustar 00 # This is the example from PEP 751, with the following differences:
# - a minor modification to the 'environments' field to use double quotes
# instead of single quotes, since that is what 'packaging' does when
# serializing markers;
# - added an index field, which was not demonstrated in the PEP 751 example.
# - removed spaces in require-python specifiers
lock-version = '1.0'
environments = ['sys_platform == "win32"', 'sys_platform == "linux"']
requires-python = '==3.12'
created-by = 'mousebender'
[[packages]]
name = 'attrs'
version = '25.1.0'
requires-python = '>=3.8'
[[packages.wheels]]
name = 'attrs-25.1.0-py3-none-any.whl'
upload-time = 2025-01-25T11:30:10.164985+00:00
url = 'https://files.pythonhosted.org/packages/fc/30/d4986a882011f9df997a55e6becd864812ccfcd821d64aac8570ee39f719/attrs-25.1.0-py3-none-any.whl'
size = 63152
hashes = {sha256 = 'c75a69e28a550a7e93789579c22aa26b0f5b83b75dc4e08fe092980051e1090a'}
[[packages.attestation-identities]]
environment = 'release-pypi'
kind = 'GitHub'
repository = 'python-attrs/attrs'
workflow = 'pypi-package.yml'
[[packages]]
name = 'cattrs'
version = '24.1.2'
requires-python = '>=3.8'
dependencies = [
{name = 'attrs'},
]
index = 'https://pypi.org/simple'
[[packages.wheels]]
name = 'cattrs-24.1.2-py3-none-any.whl'
upload-time = 2024-09-22T14:58:34.812643+00:00
url = 'https://files.pythonhosted.org/packages/c8/d5/867e75361fc45f6de75fe277dd085627a9db5ebb511a87f27dc1396b5351/cattrs-24.1.2-py3-none-any.whl'
size = 66446
hashes = {sha256 = '67c7495b760168d931a10233f979b28dc04daf853b30752246f4f8471c6d68d0'}
[[packages]]
name = 'numpy'
version = '2.2.3'
requires-python = '>=3.10'
[[packages.wheels]]
name = 'numpy-2.2.3-cp312-cp312-win_amd64.whl'
upload-time = 2025-02-13T16:51:21.821880+00:00
url = 'https://files.pythonhosted.org/packages/42/6e/55580a538116d16ae7c9aa17d4edd56e83f42126cb1dfe7a684da7925d2c/numpy-2.2.3-cp312-cp312-win_amd64.whl'
size = 12626357
hashes = {sha256 = '83807d445817326b4bcdaaaf8e8e9f1753da04341eceec705c001ff342002e5d'}
[[packages.wheels]]
name = 'numpy-2.2.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl'
upload-time = 2025-02-13T16:50:00.079662+00:00
url = 'https://files.pythonhosted.org/packages/39/04/78d2e7402fb479d893953fb78fa7045f7deb635ec095b6b4f0260223091a/numpy-2.2.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl'
size = 16116679
hashes = {sha256 = '3b787adbf04b0db1967798dba8da1af07e387908ed1553a0d6e74c084d1ceafe'}
[tool.mousebender]
command = ['.', 'lock', '--platform', 'cpython3.12-windows-x64', '--platform', 'cpython3.12-manylinux2014-x64', 'cattrs', 'numpy']
run-on = 2025-03-06T12:28:57.760769
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1768936045.8193686
packaging-26.0/tests/test_elffile.py 0000644 0000000 0000000 00000006364 15133751156 014514 0 ustar 00 import io
import pathlib
import struct
import pytest
from packaging._elffile import EIClass, EIData, ELFFile, ELFInvalid, EMachine
DIR_MANYLINUX = pathlib.Path(__file__, "..", "manylinux").resolve()
DIR_MUSLLINUX = pathlib.Path(__file__, "..", "musllinux").resolve()
BIN_MUSL_X86_64 = DIR_MUSLLINUX.joinpath("musl-x86_64").read_bytes()
@pytest.mark.parametrize(
("name", "capacity", "encoding", "machine"),
[
("x86_64-x32", EIClass.C32, EIData.Lsb, EMachine.X8664),
("x86_64-i386", EIClass.C32, EIData.Lsb, EMachine.I386),
("x86_64-amd64", EIClass.C64, EIData.Lsb, EMachine.X8664),
("armv7l-armel", EIClass.C32, EIData.Lsb, EMachine.Arm),
("armv7l-armhf", EIClass.C32, EIData.Lsb, EMachine.Arm),
("s390x-s390x", EIClass.C64, EIData.Msb, EMachine.S390),
],
)
def test_elffile_glibc(
name: str, capacity: EIClass, encoding: EIData, machine: EMachine
) -> None:
path = DIR_MANYLINUX.joinpath(f"hello-world-{name}")
with path.open("rb") as f:
ef = ELFFile(f)
assert ef.capacity == capacity
assert ef.encoding == encoding
assert ef.machine == machine
assert ef.flags is not None
@pytest.mark.parametrize(
("name", "capacity", "encoding", "machine", "interpreter"),
[
(
"aarch64",
EIClass.C64,
EIData.Lsb,
EMachine.AArc64,
"aarch64",
),
("i386", EIClass.C32, EIData.Lsb, EMachine.I386, "i386"),
("x86_64", EIClass.C64, EIData.Lsb, EMachine.X8664, "x86_64"),
],
)
def test_elffile_musl(
name: str, capacity: EIClass, encoding: EIData, machine: EMachine, interpreter: str
) -> None:
path = DIR_MUSLLINUX.joinpath(f"musl-{name}")
with path.open("rb") as f:
ef = ELFFile(f)
assert ef.capacity == capacity
assert ef.encoding == encoding
assert ef.machine == machine
assert ef.interpreter == f"/lib/ld-musl-{interpreter}.so.1"
@pytest.mark.parametrize(
"data",
[
# Too short for magic.
b"\0",
# Enough for magic, but not ELF.
b"#!/bin/bash" + b"\0" * 16,
# ELF, but unknown byte declaration.
b"\x7fELF\3" + b"\0" * 16,
],
ids=["no-magic", "wrong-magic", "unknown-format"],
)
def test_elffile_bad_ident(data: bytes) -> None:
with pytest.raises(ELFInvalid):
ELFFile(io.BytesIO(data))
def test_elffile_no_section() -> None:
"""Enough for magic, but not the section definitions."""
data = BIN_MUSL_X86_64[:25]
with pytest.raises(ELFInvalid):
ELFFile(io.BytesIO(data))
def test_elffile_invalid_section() -> None:
"""Enough for section definitions, but not the actual sections."""
data = BIN_MUSL_X86_64[:58]
assert ELFFile(io.BytesIO(data)).interpreter is None
def test_elffle_no_interpreter_section() -> None:
ef = ELFFile(io.BytesIO(BIN_MUSL_X86_64))
# Change all sections to *not* PT_INTERP.
data = BIN_MUSL_X86_64
for i in range(ef._e_phnum + 1):
sb = ef._e_phoff + ef._e_phentsize * i
se = sb + ef._e_phentsize
section = struct.unpack(ef._p_fmt, data[sb:se])
data = data[:sb] + struct.pack(ef._p_fmt, 0, *section[1:]) + data[se:]
assert ELFFile(io.BytesIO(data)).interpreter is None
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1768936045.8193686
packaging-26.0/tests/test_licenses.py 0000644 0000000 0000000 00000000442 15133751156 014702 0 ustar 00 from packaging.licenses._spdx import EXCEPTIONS, LICENSES
def test_licenses() -> None:
for license_id in LICENSES:
assert license_id == license_id.lower()
def test_exceptions() -> None:
for exception_id in EXCEPTIONS:
assert exception_id == exception_id.lower()
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1768936045.8193686
packaging-26.0/tests/test_manylinux.py 0000644 0000000 0000000 00000015446 15133751156 015133 0 ustar 00 from __future__ import annotations
try:
import ctypes
except ImportError:
ctypes = None # type: ignore[assignment]
import os
import pathlib
import platform
import re
import sys
import types
import typing
if typing.TYPE_CHECKING:
from collections.abc import Generator
import pretend
import pytest
from packaging import _manylinux
from packaging._manylinux import (
_get_glibc_version,
_glibc_version_string,
_glibc_version_string_confstr,
_glibc_version_string_ctypes,
_GLibCVersion,
_is_compatible,
_parse_elf,
_parse_glibc_version,
)
@pytest.fixture(autouse=True)
def clear_lru_cache() -> Generator[None, None, None]:
yield
_get_glibc_version.cache_clear()
@pytest.fixture
def manylinux_module(monkeypatch: pytest.MonkeyPatch) -> types.ModuleType:
monkeypatch.setattr(_manylinux, "_get_glibc_version", lambda *args: (2, 20))
module_name = "_manylinux"
module = types.ModuleType(module_name)
monkeypatch.setitem(sys.modules, module_name, module)
return module
@pytest.mark.parametrize("tf", [True, False])
@pytest.mark.parametrize(
("attribute", "glibc"), [("1", (2, 5)), ("2010", (2, 12)), ("2014", (2, 17))]
)
def test_module_declaration(
monkeypatch: pytest.MonkeyPatch,
manylinux_module: types.ModuleType,
attribute: str,
glibc: tuple[int, int],
tf: bool,
) -> None:
manylinux = f"manylinux{attribute}_compatible"
monkeypatch.setattr(manylinux_module, manylinux, tf, raising=False)
glibc_version = _GLibCVersion(glibc[0], glibc[1])
res = _is_compatible("x86_64", glibc_version)
assert tf is res
@pytest.mark.parametrize(
("attribute", "glibc"), [("1", (2, 5)), ("2010", (2, 12)), ("2014", (2, 17))]
)
def test_module_declaration_missing_attribute(
monkeypatch: pytest.MonkeyPatch,
manylinux_module: types.ModuleType,
attribute: str,
glibc: tuple[int, int],
) -> None:
manylinux = f"manylinux{attribute}_compatible"
monkeypatch.delattr(manylinux_module, manylinux, raising=False)
glibc_version = _GLibCVersion(glibc[0], glibc[1])
assert _is_compatible("x86_64", glibc_version)
@pytest.mark.parametrize(
("version", "compatible"), [((2, 0), True), ((2, 5), True), ((2, 10), False)]
)
def test_is_manylinux_compatible_glibc_support(
version: tuple[int, int], compatible: bool, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setitem(sys.modules, "_manylinux", None)
monkeypatch.setattr(_manylinux, "_get_glibc_version", lambda: (2, 5))
glibc_version = _GLibCVersion(version[0], version[1])
assert bool(_is_compatible("any", glibc_version)) == compatible
@pytest.mark.parametrize("version_str", ["glibc-2.4.5", "2"])
def test_check_glibc_version_warning(version_str: str) -> None:
msg = f"Expected glibc version with 2 components major.minor, got: {version_str}"
with pytest.warns(RuntimeWarning, match=re.escape(msg)):
_parse_glibc_version(version_str)
@pytest.mark.skipif(not ctypes, reason="requires ctypes") # type: ignore[truthy-bool]
@pytest.mark.parametrize(
("version_str", "expected"),
[
# Be very explicit about bytes and Unicode for Python 2 testing.
(b"2.4", "2.4"),
("2.4", "2.4"),
],
)
def test_glibc_version_string(
version_str: str | bytes, expected: str, monkeypatch: pytest.MonkeyPatch
) -> None:
class LibcVersion:
def __init__(self, version_str: str | bytes) -> None:
self.version_str = version_str
def __call__(self) -> str | bytes:
return self.version_str
class ProcessNamespace:
def __init__(self, libc_version: LibcVersion) -> None:
self.gnu_get_libc_version = libc_version
process_namespace = ProcessNamespace(LibcVersion(version_str))
monkeypatch.setattr(ctypes, "CDLL", lambda _: process_namespace)
monkeypatch.setattr(_manylinux, "_glibc_version_string_confstr", lambda: False)
assert _glibc_version_string() == expected
del process_namespace.gnu_get_libc_version
assert _glibc_version_string() is None
def test_glibc_version_string_confstr(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(os, "confstr", lambda _: "glibc 2.20", raising=False)
assert _glibc_version_string_confstr() == "2.20"
def test_glibc_version_string_fail(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(os, "confstr", lambda _: None, raising=False)
monkeypatch.setitem(sys.modules, "ctypes", None)
assert _glibc_version_string() is None
assert _get_glibc_version() == (-1, -1)
@pytest.mark.parametrize(
"failure",
[pretend.raiser(ValueError), pretend.raiser(OSError), lambda _: "XXX"],
)
def test_glibc_version_string_confstr_fail(
monkeypatch: pytest.MonkeyPatch, failure: typing.Callable[[int], str | None]
) -> None:
monkeypatch.setattr(os, "confstr", failure, raising=False)
assert _glibc_version_string_confstr() is None
def test_glibc_version_string_confstr_missing(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.delattr(os, "confstr", raising=False)
assert _glibc_version_string_confstr() is None
def test_glibc_version_string_ctypes_missing(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setitem(sys.modules, "ctypes", None)
assert _glibc_version_string_ctypes() is None
@pytest.mark.xfail(ctypes is None, reason="ctypes not available")
def test_glibc_version_string_ctypes_raise_oserror(
monkeypatch: pytest.MonkeyPatch,
) -> None:
def patched_cdll(_name: str) -> None:
raise OSError("Dynamic loading not supported")
monkeypatch.setattr(ctypes, "CDLL", patched_cdll)
assert _glibc_version_string_ctypes() is None
@pytest.mark.skipif(platform.system() != "Linux", reason="requires Linux")
def test_is_manylinux_compatible_old() -> None:
# Assuming no one is running this test with a version of glibc released in
# 1997.
assert _is_compatible("any", _GLibCVersion(2, 0))
def test_is_manylinux_compatible(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(_manylinux, "_glibc_version_string", lambda: "2.4")
assert _is_compatible("any", _GLibCVersion(2, 4))
def test_glibc_version_string_none(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(_manylinux, "_glibc_version_string", lambda: None)
assert not _is_compatible("any", _GLibCVersion(2, 4))
@pytest.mark.parametrize(
"content", [None, "invalid-magic", "invalid-class", "invalid-data", "too-short"]
)
def test_parse_elf_bad_executable(content: str | None) -> None:
path_str: str | None
if content:
path = pathlib.Path(__file__).parent / "manylinux" / f"hello-world-{content}"
path_str = os.fsdecode(path)
else:
path_str = None
# None is not supported in the type annotation, but it was tested before.
with _parse_elf(path_str) as ef: # type: ignore[arg-type]
assert ef is None
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1768936045.8193686
packaging-26.0/tests/test_markers.py 0000644 0000000 0000000 00000043276 15133751156 014555 0 ustar 00 # This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import annotations
import collections
import itertools
import os
import platform
import sys
from typing import cast
from unittest import mock
import pytest
from packaging._parser import Node
from packaging.markers import (
InvalidMarker,
Marker,
UndefinedComparison,
default_environment,
format_full_version,
)
VARIABLES = [
"extra",
"implementation_name",
"implementation_version",
"os_name",
"platform_machine",
"platform_release",
"platform_system",
"platform_version",
"python_full_version",
"python_version",
"platform_python_implementation",
"sys_platform",
]
PEP_345_VARIABLES = [
"os.name",
"sys.platform",
"platform.version",
"platform.machine",
"platform.python_implementation",
]
SETUPTOOLS_VARIABLES = ["python_implementation"]
OPERATORS = ["===", "==", ">=", "<=", "!=", "~=", ">", "<", "in", "not in"]
VALUES = [
"1.0",
"5.6a0",
"dog",
"freebsd",
"literally any string can go here",
"things @#4 dsfd (((",
]
class TestNode:
@pytest.mark.parametrize("value", ["one", "two", None, 3, 5, []])
def test_accepts_value(self, value: str | None | int | list[str]) -> None:
assert Node(value).value == value # type: ignore[arg-type]
@pytest.mark.parametrize("value", ["one", "two"])
def test_str(self, value: str) -> None:
assert str(Node(value)) == str(value)
@pytest.mark.parametrize("value", ["one", "two"])
def test_repr(self, value: str) -> None:
assert repr(Node(value)) == f""
def test_base_class(self) -> None:
with pytest.raises(NotImplementedError):
Node("cover all the code").serialize()
class TestOperatorEvaluation:
def test_prefers_pep440(self) -> None:
assert Marker('"2.7.9" < python_full_version').evaluate(
dict(python_full_version="2.7.10")
)
assert not Marker('"2.7.9" < python_full_version').evaluate(
dict(python_full_version="2.7.8")
)
def test_new_string_rules(self) -> None:
assert not Marker('"b" < python_full_version').evaluate(
dict(python_full_version="c")
)
assert not Marker('"b" < python_full_version').evaluate(
dict(python_full_version="a")
)
assert not Marker('"b" > "a"').evaluate(dict(a="a"))
assert not Marker('"b" < "a"').evaluate(dict(a="a"))
assert not Marker('"b" >= "a"').evaluate(dict(a="a"))
assert not Marker('"b" <= "a"').evaluate(dict(a="a"))
assert Marker('"a" <= "a"').evaluate(dict(a="a"))
def test_fails_when_undefined(self) -> None:
with pytest.raises(UndefinedComparison):
Marker("'2.7.0' ~= os_name").evaluate()
def test_allows_prerelease(self) -> None:
assert Marker('python_full_version > "3.6.2"').evaluate(
{"python_full_version": "3.11.0a5"}
)
FakeVersionInfo = collections.namedtuple(
"FakeVersionInfo", ["major", "minor", "micro", "releaselevel", "serial"]
)
class TestDefaultEnvironment:
def test_matches_expected(self) -> None:
environment = default_environment()
iver = (
f"{sys.implementation.version.major}."
f"{sys.implementation.version.minor}."
f"{sys.implementation.version.micro}"
)
if sys.implementation.version.releaselevel != "final":
iver = (
f"{iver}{sys.implementation.version.releaselevel[0]}"
f"{sys.implementation.version.serial}"
)
assert environment == {
"implementation_name": sys.implementation.name,
"implementation_version": iver,
"os_name": os.name,
"platform_machine": platform.machine(),
"platform_release": platform.release(),
"platform_system": platform.system(),
"platform_version": platform.version(),
"python_full_version": platform.python_version(),
"platform_python_implementation": platform.python_implementation(),
"python_version": ".".join(platform.python_version_tuple()[:2]),
"sys_platform": sys.platform,
}
def test_multidigit_minor_version(self, monkeypatch: pytest.MonkeyPatch) -> None:
version_info = (3, 10, 0, "final", 0)
monkeypatch.setattr(sys, "version_info", version_info, raising=False)
monkeypatch.setattr(platform, "python_version", lambda: "3.10.0", raising=False)
monkeypatch.setattr(
platform, "python_version_tuple", lambda: ("3", "10", "0"), raising=False
)
environment = default_environment()
assert environment["python_version"] == "3.10"
def tests_when_releaselevel_final(self) -> None:
v = FakeVersionInfo(3, 4, 2, "final", 0)
assert format_full_version(v) == "3.4.2" # type: ignore[arg-type]
def tests_when_releaselevel_not_final(self) -> None:
v = FakeVersionInfo(3, 4, 2, "beta", 4)
assert format_full_version(v) == "3.4.2b4" # type: ignore[arg-type]
class TestMarker:
@pytest.mark.parametrize(
"marker_string",
[
"{} {} {!r}".format(*i)
for i in itertools.product(VARIABLES, OPERATORS, VALUES)
]
+ [
"{2!r} {1} {0}".format(*i)
for i in itertools.product(VARIABLES, OPERATORS, VALUES)
],
)
def test_parses_valid(self, marker_string: str) -> None:
Marker(marker_string)
@pytest.mark.parametrize(
"marker_string",
[
"this_isnt_a_real_variable >= '1.0'",
"python_version",
"(python_version)",
"python_version >= 1.0 and (python_version)",
'(python_version == "2.7" and os_name == "linux"',
'(python_version == "2.7") with random text',
],
)
def test_parses_invalid(self, marker_string: str) -> None:
with pytest.raises(InvalidMarker):
Marker(marker_string)
@pytest.mark.parametrize(
("marker_string", "expected"),
[
# Test the different quoting rules
("python_version == '2.7'", 'python_version == "2.7"'),
('python_version == "2.7"', 'python_version == "2.7"'),
# Test and/or expressions
(
'python_version == "2.7" and os_name == "linux"',
'python_version == "2.7" and os_name == "linux"',
),
(
'python_version == "2.7" or os_name == "linux"',
'python_version == "2.7" or os_name == "linux"',
),
(
'python_version == "2.7" and os_name == "linux" or '
'sys_platform == "win32"',
'python_version == "2.7" and os_name == "linux" or '
'sys_platform == "win32"',
),
# Test nested expressions and grouping with ()
('(python_version == "2.7")', 'python_version == "2.7"'),
(
'(python_version == "2.7" and sys_platform == "win32")',
'python_version == "2.7" and sys_platform == "win32"',
),
(
'python_version == "2.7" and (sys_platform == "win32" or '
'sys_platform == "linux")',
'python_version == "2.7" and (sys_platform == "win32" or '
'sys_platform == "linux")',
),
],
)
def test_str_repr_eq_hash(self, marker_string: str, expected: str) -> None:
m = Marker(marker_string)
assert str(m) == expected
assert repr(m) == f""
# Objects created from the same string should be equal.
assert m == Marker(marker_string)
# Objects created from the equivalent strings should also be equal.
assert m == Marker(expected)
# Objects created from the same string should have the same hash.
assert hash(Marker(marker_string)) == hash(Marker(marker_string))
# Objects created from equivalent strings should also have the same hash.
assert hash(Marker(marker_string)) == hash(Marker(expected))
@pytest.mark.parametrize(
("example1", "example2"),
[
# Test trivial comparisons.
('python_version == "2.7"', 'python_version == "3.7"'),
(
'python_version == "2.7"',
'python_version == "2.7" and os_name == "linux"',
),
(
'python_version == "2.7"',
'(python_version == "2.7" and os_name == "linux")',
),
# Test different precedence.
(
'python_version == "2.7" and (os_name == "linux" or '
'sys_platform == "win32")',
'python_version == "2.7" and os_name == "linux" or '
'sys_platform == "win32"',
),
],
)
def test_different_markers_different_hashes(
self, example1: str, example2: str
) -> None:
marker1, marker2 = Marker(example1), Marker(example2)
# Markers created from strings that are not equivalent should differ.
assert marker1 != marker2
# Different Marker objects should have different hashes.
assert hash(marker1) != hash(marker2)
def test_compare_markers_to_other_objects(self) -> None:
# Markers should not be comparable to other kinds of objects.
assert Marker("os_name == 'nt'") != "os_name == 'nt'"
def test_environment_assumes_empty_extra(self) -> None:
assert Marker('extra == "im_valid"').evaluate() is False
def test_environment_with_extra_none(self) -> None:
# GIVEN
marker_str = 'extra == "im_valid"'
# Pretend that this is dict[str, str], even though it's not. This is a
# test for being bug-for-bug compatible with the older implementation.
environment = cast("dict[str, str]", {"extra": None})
# WHEN
marker = Marker(marker_str)
# THEN
assert marker.evaluate(environment) is False
def test_environment_with_no_extras(self) -> None:
# Environment is set but no 'extra' key is present; branch only hit on
# non-metadata context.
marker = Marker("os_name == 'foo'")
assert marker.evaluate({"os_name": "foo"}, context="requirement")
assert not marker.evaluate({"os_name": "bar"}, context="requirement")
@pytest.mark.parametrize(
("marker_string", "environment", "expected"),
[
(f"os_name == '{os.name}'", None, True),
("os_name == 'foo'", {"os_name": "foo"}, True),
("os_name == 'foo'", {"os_name": "bar"}, False),
("'2.7' in python_version", {"python_version": "2.7.5"}, True),
("'2.7' not in python_version", {"python_version": "2.7"}, False),
(
"os_name == 'foo' and python_version ~= '2.7.0'",
{"os_name": "foo", "python_version": "2.7.6"},
True,
),
(
"python_version ~= '2.7.0' and (os_name == 'foo' or os_name == 'bar')",
{"os_name": "foo", "python_version": "2.7.4"},
True,
),
(
"python_version ~= '2.7.0' and (os_name == 'foo' or os_name == 'bar')",
{"os_name": "bar", "python_version": "2.7.4"},
True,
),
(
"python_version ~= '2.7.0' and (os_name == 'foo' or os_name == 'bar')",
{"os_name": "other", "python_version": "2.7.4"},
False,
),
("extra == 'security'", {"extra": "quux"}, False),
("extra == 'security'", {"extra": "security"}, True),
("extra == 'SECURITY'", {"extra": "security"}, True),
("extra == 'security'", {"extra": "SECURITY"}, True),
("extra == 'pep-685-norm'", {"extra": "PEP_685...norm"}, True),
(
"extra == 'Different.punctuation..is...equal'",
{"extra": "different__punctuation_is_EQUAL"},
True,
),
],
)
def test_evaluates(
self, marker_string: str, environment: dict[str, str] | None, expected: bool
) -> None:
args = () if environment is None else (environment,)
assert Marker(marker_string).evaluate(*args) == expected
@pytest.mark.parametrize(
"marker_string",
[
"{} {} {!r}".format(*i)
for i in itertools.product(PEP_345_VARIABLES, OPERATORS, VALUES)
]
+ [
"{2!r} {1} {0}".format(*i)
for i in itertools.product(PEP_345_VARIABLES, OPERATORS, VALUES)
],
)
def test_parses_pep345_valid(self, marker_string: str) -> None:
Marker(marker_string)
@pytest.mark.parametrize(
("marker_string", "environment", "expected"),
[
(f"os.name == '{os.name}'", None, True),
("sys.platform == 'win32'", {"sys_platform": "linux2"}, False),
("platform.version in 'Ubuntu'", {"platform_version": "#39"}, False),
("platform.machine=='x86_64'", {"platform_machine": "x86_64"}, True),
(
"platform.python_implementation=='Jython'",
{"platform_python_implementation": "CPython"},
False,
),
(
"python_version == '2.5' and platform.python_implementation!= 'Jython'",
{"python_version": "2.7"},
False,
),
],
)
def test_evaluate_pep345_markers(
self, marker_string: str, environment: dict[str, str] | None, expected: bool
) -> None:
args = () if environment is None else (environment,)
assert Marker(marker_string).evaluate(*args) == expected
@pytest.mark.parametrize(
"marker_string",
[
"{} {} {!r}".format(*i)
for i in itertools.product(SETUPTOOLS_VARIABLES, OPERATORS, VALUES)
]
+ [
"{2!r} {1} {0}".format(*i)
for i in itertools.product(SETUPTOOLS_VARIABLES, OPERATORS, VALUES)
],
)
def test_parses_setuptools_legacy_valid(self, marker_string: str) -> None:
Marker(marker_string)
def test_evaluate_setuptools_legacy_markers(self) -> None:
marker_string = "python_implementation=='Jython'"
args = ({"platform_python_implementation": "CPython"},)
assert Marker(marker_string).evaluate(*args) is False
def test_extra_str_normalization(self) -> None:
raw_name = "S_P__A_M"
normalized_name = "s-p-a-m"
lhs = f"{raw_name!r} == extra"
rhs = f"extra == {raw_name!r}"
assert str(Marker(lhs)) == f'"{normalized_name}" == extra'
assert str(Marker(rhs)) == f'extra == "{normalized_name}"'
def test_python_full_version_untagged_user_provided(self) -> None:
"""A user-provided python_full_version ending with a + is also repaired."""
assert Marker("python_full_version < '3.12'").evaluate(
{"python_full_version": "3.11.1+"}
)
def test_python_full_version_untagged(self) -> None:
with mock.patch("platform.python_version", return_value="3.11.1+"):
assert Marker("python_full_version < '3.12'").evaluate()
@pytest.mark.parametrize("variable", ["extras", "dependency_groups"])
@pytest.mark.parametrize(
("expression", "result"),
[
pytest.param('"foo" in {0}', True, id="value-in-foo"),
pytest.param('"bar" in {0}', True, id="value-in-bar"),
pytest.param('"baz" in {0}', False, id="value-not-in"),
pytest.param('"baz" not in {0}', True, id="value-not-in-negated"),
pytest.param('"foo" in {0} and "bar" in {0}', True, id="and-in"),
pytest.param('"foo" in {0} or "bar" in {0}', True, id="or-in"),
pytest.param(
'"baz" in {0} and "foo" in {0}', False, id="short-circuit-and"
),
pytest.param('"foo" in {0} or "baz" in {0}', True, id="short-circuit-or"),
pytest.param('"Foo" in {0}', True, id="case-sensitive"),
],
)
def test_extras_and_dependency_groups(
self, variable: str, expression: str, result: bool
) -> None:
environment = {variable: {"foo", "bar"}}
assert Marker(expression.format(variable)).evaluate(environment) == result
@pytest.mark.parametrize("variable", ["extras", "dependency_groups"])
def test_extras_and_dependency_groups_disallowed(self, variable: str) -> None:
marker = Marker(f'"foo" in {variable}')
assert not marker.evaluate(context="lock_file")
with pytest.raises(KeyError):
marker.evaluate()
with pytest.raises(KeyError):
marker.evaluate(context="requirement")
@pytest.mark.parametrize(
("marker_string", "environment", "expected"),
[
('extra == "v2"', None, False),
('extra == "v2"', {"extra": ""}, False),
('extra == "v2"', {"extra": "v2"}, True),
('extra == "v2"', {"extra": "v2a3"}, False),
('extra == "v2a3"', {"extra": "v2"}, False),
('extra == "v2a3"', {"extra": "v2a3"}, True),
],
)
def test_version_like_equality(
self, marker_string: str, environment: dict[str, str] | None, expected: bool
) -> None:
"""
Test for issue #938: Extras are meant to be literal strings, even if
they look like versions, and therefore should not be parsed as version.
"""
marker = Marker(marker_string)
assert marker.evaluate(environment) is expected
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1768936045.8193686
packaging-26.0/tests/test_metadata.py 0000644 0000000 0000000 00000125512 15133751156 014663 0 ustar 00 from __future__ import annotations
import email.message
import inspect
import pathlib
import textwrap
import pytest
from packaging import metadata, requirements, specifiers, utils, version
from packaging.metadata import ExceptionGroup, RawMetadata
class TestRawMetadata:
@pytest.mark.parametrize("raw_field", sorted(metadata._STRING_FIELDS))
def test_non_repeating_fields_only_once(self, raw_field: str) -> None:
data = "VaLuE"
header_field = metadata._RAW_TO_EMAIL_MAPPING[raw_field]
single_header = f"{header_field}: {data}"
raw, unparsed = metadata.parse_email(single_header)
assert not unparsed
assert len(raw) == 1
assert raw_field in raw
assert raw[raw_field] == data # type: ignore[literal-required]
@pytest.mark.parametrize("raw_field", sorted(metadata._STRING_FIELDS))
def test_non_repeating_fields_repeated(self, raw_field: str) -> None:
header_field = metadata._RAW_TO_EMAIL_MAPPING[raw_field]
data = "VaLuE"
single_header = f"{header_field}: {data}"
repeated_header = "\n".join([single_header] * 2)
raw, unparsed = metadata.parse_email(repeated_header)
assert not raw
assert len(unparsed) == 1
assert header_field in unparsed
assert unparsed[header_field] == [data] * 2
@pytest.mark.parametrize("raw_field", sorted(metadata._LIST_FIELDS))
def test_repeating_fields_only_once(self, raw_field: str) -> None:
data = "VaLuE"
header_field = metadata._RAW_TO_EMAIL_MAPPING[raw_field]
single_header = f"{header_field}: {data}"
raw, unparsed = metadata.parse_email(single_header)
assert not unparsed
assert len(raw) == 1
assert raw_field in raw
assert raw[raw_field] == [data] # type: ignore[literal-required]
@pytest.mark.parametrize("raw_field", sorted(metadata._LIST_FIELDS))
def test_repeating_fields_repeated(self, raw_field: str) -> None:
header_field = metadata._RAW_TO_EMAIL_MAPPING[raw_field]
data = "VaLuE"
single_header = f"{header_field}: {data}"
repeated_header = "\n".join([single_header] * 2)
raw, unparsed = metadata.parse_email(repeated_header)
assert not unparsed
assert len(raw) == 1
assert raw_field in raw
assert raw[raw_field] == [data] * 2 # type: ignore[literal-required]
@pytest.mark.parametrize(
("given", "expected"),
[
("A", ["A"]),
("A ", ["A"]),
(" A", ["A"]),
("A, B", ["A", "B"]),
("A,B", ["A", "B"]),
(" A, B", ["A", "B"]),
("A,B ", ["A", "B"]),
("A B", ["A B"]),
],
)
def test_keywords(self, given: str, expected: list[str]) -> None:
header = f"Keywords: {given}"
raw, unparsed = metadata.parse_email(header)
assert not unparsed
assert len(raw) == 1
assert "keywords" in raw
assert raw["keywords"] == expected
@pytest.mark.parametrize(
("given", "expected"),
[
("", {"": ""}),
("A", {"A": ""}),
("A,B", {"A": "B"}),
("A, B", {"A": "B"}),
(" A,B", {"A": "B"}),
("A,B ", {"A": "B"}),
("A,B,C", {"A": "B,C"}),
],
)
def test_project_urls_parsing(self, given: str, expected: dict[str, str]) -> None:
header = f"project-url: {given}"
raw, unparsed = metadata.parse_email(header)
assert not unparsed
assert len(raw) == 1
assert "project_urls" in raw
assert raw["project_urls"] == expected
def test_duplicate_project_urls(self) -> None:
header = "project-url: A, B\nproject-url: A, C"
raw, unparsed = metadata.parse_email(header)
assert not raw
assert len(unparsed) == 1
assert "project-url" in unparsed
assert unparsed["project-url"] == ["A, B", "A, C"]
def test_str_input(self) -> None:
name = "Tarek Ziadé"
header = f"author: {name}"
raw, unparsed = metadata.parse_email(header)
assert not unparsed
assert len(raw) == 1
assert "author" in raw
assert raw["author"] == name
def test_bytes_input(self) -> None:
name = "Tarek Ziadé"
header = f"author: {name}".encode()
raw, unparsed = metadata.parse_email(header)
assert not unparsed
assert len(raw) == 1
assert "author" in raw
assert raw["author"] == name
def test_header_mojibake(self) -> None:
value = "\xc0msterdam"
header_name = "value"
header_bytes = f"{header_name}: {value}".encode("latin1")
raw, unparsed = metadata.parse_email(header_bytes)
# Sanity check
with pytest.raises(UnicodeDecodeError):
header_bytes.decode("utf-8")
assert not raw
assert len(unparsed) == 1
assert header_name in unparsed
assert unparsed[header_name] == [value]
@pytest.mark.parametrize("given", ["hello", "description: hello", b"hello"])
def test_description(self, given: str | bytes) -> None:
raw, unparsed = metadata.parse_email(given)
assert not unparsed
assert len(raw) == 1
assert "description" in raw
assert raw["description"] == "hello"
def test_description_non_utf8(self) -> None:
header = "\xc0msterdam"
header_bytes = header.encode("latin1")
raw, unparsed = metadata.parse_email(header_bytes)
assert not raw
assert len(unparsed) == 1
assert "description" in unparsed
# TODO: type annotations are not happy about this, investigate.
assert unparsed["description"] == [header_bytes] # type: ignore[comparison-overlap]
@pytest.mark.parametrize(
("given", "expected"),
[
("description: 1\ndescription: 2", ["1", "2"]),
("description: 1\n\n2", ["1", "2"]),
("description: 1\ndescription: 2\n\n3", ["1", "2", "3"]),
],
)
def test_description_multiple(
self, given: str | bytes, expected: list[str]
) -> None:
raw, unparsed = metadata.parse_email(given)
assert not raw
assert len(unparsed) == 1
assert "description" in unparsed
assert unparsed["description"] == expected
def test_lowercase_keys(self) -> None:
header = "AUTHOR: Tarek Ziadé\nWhatever: Else"
raw, unparsed = metadata.parse_email(header)
assert len(raw) == 1
assert "author" in raw
assert len(unparsed) == 1
assert "whatever" in unparsed
def test_complete(self) -> None:
"""Test all fields (except `Obsoletes-Dist`).
`Obsoletes-Dist` was sacrificed to provide a value for `Dynamic`.
"""
path = pathlib.Path(__file__).parent / "metadata" / "everything.metadata"
with path.open("r", encoding="utf-8") as file:
metadata_contents = file.read()
raw, unparsed = metadata.parse_email(metadata_contents)
assert len(unparsed) == 1 # "ThisIsNotReal" key
assert unparsed["thisisnotreal"] == ["Hello!"]
assert len(raw) == 28
assert raw["metadata_version"] == "2.5"
assert raw["name"] == "BeagleVote"
assert raw["version"] == "1.0a2"
assert raw["platforms"] == ["ObscureUnix", "RareDOS"]
assert raw["supported_platforms"] == ["RedHat 7.2", "i386-win32-2791"]
assert raw["summary"] == "A module for collecting votes from beagles."
assert (
raw["description_content_type"]
== "text/markdown; charset=UTF-8; variant=GFM"
)
assert raw["keywords"] == ["dog", "puppy", "voting", "election"]
assert raw["home_page"] == "http://www.example.com/~cschultz/bvote/"
assert raw["download_url"] == "…/BeagleVote-0.45.tgz"
assert raw["author"] == (
"C. Schultz, Universal Features Syndicate,\n"
" Los Angeles, CA "
)
assert raw["author_email"] == '"C. Schultz" '
assert raw["maintainer"] == (
"C. Schultz, Universal Features Syndicate,\n"
" Los Angeles, CA "
)
assert raw["maintainer_email"] == '"C. Schultz" '
assert raw["license"] == (
"This software may only be obtained by sending the\n"
" author a postcard, and then the user promises not\n"
" to redistribute it."
)
assert raw["license_expression"] == "Apache-2.0 OR BSD-2-Clause"
assert raw["license_files"] == ["LICENSE.APACHE", "LICENSE.BSD"]
assert raw["classifiers"] == [
"Development Status :: 4 - Beta",
"Environment :: Console (Text Based)",
]
assert raw["provides_extra"] == ["pdf"]
assert raw["requires_dist"] == [
"reportlab; extra == 'pdf'",
"pkginfo",
"PasteDeploy",
"zope.interface (>3.5.0)",
"pywin32 >1.0; sys_platform == 'win32'",
]
assert raw["requires_python"] == ">=3"
assert raw["requires_external"] == [
"C",
"libpng (>=1.5)",
'make; sys_platform != "win32"',
]
assert raw["project_urls"] == {
"Bug Tracker": "http://bitbucket.org/tarek/distribute/issues/",
"Documentation": "https://example.com/BeagleVote",
}
assert raw["provides_dist"] == [
"OtherProject",
"AnotherProject (3.4)",
'virtual_package; python_version >= "3.4"',
]
assert raw["dynamic"] == ["Obsoletes-Dist"]
assert raw["description"] == "This description intentionally left blank.\n"
assert raw["import_names"] == ["beaglevote", "_beaglevote ; private"]
assert raw["import_namespaces"] == ["spam", "_bacon ; private"]
class TestExceptionGroup:
def test_attributes(self) -> None:
individual_exception = Exception("not important")
exc = metadata.ExceptionGroup("message", [individual_exception])
assert exc.message == "message"
assert list(exc.exceptions) == [individual_exception]
def test_repr(self) -> None:
individual_exception = RuntimeError("not important")
exc = metadata.ExceptionGroup("message", [individual_exception])
assert individual_exception.__class__.__name__ in repr(exc)
_RAW_EXAMPLE: RawMetadata = {
"metadata_version": "2.5",
"name": "packaging",
"version": "2023.0.0",
}
class TestMetadata:
def _invalid_with_cause(
self,
meta: metadata.Metadata,
attr: str,
cause: type[BaseException] | None = None,
*,
field: str | None = None,
) -> None:
if field is None:
field = attr
with pytest.raises(metadata.InvalidMetadata) as exc_info:
getattr(meta, attr)
exc = exc_info.value
assert exc.field == field
if cause is None:
assert exc.__cause__ is None
else:
assert isinstance(exc.__cause__, cause)
def test_from_email(self) -> None:
metadata_version = "2.5"
meta = metadata.Metadata.from_email(
f"Metadata-Version: {metadata_version}", validate=False
)
assert meta.metadata_version == metadata_version
assert meta.import_names is None
def test_from_email_empty_import_name(self) -> None:
meta = metadata.Metadata.from_email(
"Metadata-Version: 2.5\nImport-Name:\n", validate=False
)
assert meta.import_names == []
def test_from_email_unparsed(self) -> None:
with pytest.raises(ExceptionGroup) as exc_info:
metadata.Metadata.from_email("Hello: PyPA")
assert len(exc_info.value.exceptions) == 1
assert isinstance(exc_info.value.exceptions[0], metadata.InvalidMetadata)
def test_from_email_validate(self) -> None:
with pytest.raises(ExceptionGroup):
# Lacking all required fields.
metadata.Metadata.from_email("Name: packaging", validate=True)
def test_from_email_unparsed_valid_field_name(self) -> None:
with pytest.raises(ExceptionGroup):
metadata.Metadata.from_email(
"Project-URL: A, B\nProject-URL: A, C", validate=True
)
def test_required_fields(self) -> None:
meta = metadata.Metadata.from_raw(_RAW_EXAMPLE)
assert meta.metadata_version == _RAW_EXAMPLE["metadata_version"]
@pytest.mark.parametrize("field", list(_RAW_EXAMPLE.keys()))
def test_required_fields_missing(self, field: str) -> None:
required_fields = _RAW_EXAMPLE.copy()
del required_fields[field] # type: ignore[misc]
with pytest.raises(ExceptionGroup):
metadata.Metadata.from_raw(required_fields)
def test_raw_validate_unrecognized_field(self) -> None:
raw: RawMetadata = {
"metadata_version": "2.3",
"name": "packaging",
"version": "2023.0.0",
}
# Safety check (always true)
assert metadata.Metadata.from_raw(raw, validate=True) # type: ignore[truthy-bool]
# Misspelled; missing an "i":
raw["dynamc"] = ["Obsoletes-Dist"] # type: ignore[typeddict-unknown-key]
with pytest.raises(ExceptionGroup):
metadata.Metadata.from_raw(raw, validate=True)
def test_raw_data_not_mutated(self) -> None:
raw = _RAW_EXAMPLE.copy()
meta = metadata.Metadata.from_raw(raw, validate=True)
assert meta.version == version.Version(_RAW_EXAMPLE["version"])
assert raw == _RAW_EXAMPLE
def test_caching(self) -> None:
meta = metadata.Metadata.from_raw(_RAW_EXAMPLE, validate=True)
assert meta.version is meta.version
def test_from_raw_validate(self) -> None:
required_fields = _RAW_EXAMPLE.copy()
required_fields["version"] = "-----"
with pytest.raises(ExceptionGroup):
# Multiple things to trigger a validation error:
# invalid version, missing keys, etc.
metadata.Metadata.from_raw(required_fields)
@pytest.mark.parametrize("meta_version", ["2.2", "2.3"])
def test_metadata_version_field_introduction(self, meta_version: str) -> None:
raw: RawMetadata = {
"metadata_version": meta_version,
"name": "packaging",
"version": "2023.0.0",
"dynamic": ["Obsoletes-Dist"], # Introduced in 2.2.
}
assert metadata.Metadata.from_raw(raw, validate=True) # type: ignore[truthy-bool]
@pytest.mark.parametrize("meta_version", ["1.0", "1.1", "1.2", "2.1"])
def test_metadata_version_field_introduction_mismatch(
self, meta_version: str
) -> None:
raw: RawMetadata = {
"metadata_version": meta_version,
"name": "packaging",
"version": "2023.0.0",
"dynamic": ["Obsoletes-Dist"], # Introduced in 2.2.
}
with pytest.raises(ExceptionGroup):
metadata.Metadata.from_raw(raw, validate=True)
@pytest.mark.parametrize(
"attribute",
[
"description",
"home_page",
"download_url",
"author",
"author_email",
"maintainer",
"maintainer_email",
"license",
],
)
def test_single_value_unvalidated_attribute(self, attribute: str) -> None:
value = "Not important"
meta = metadata.Metadata.from_raw({attribute: value}, validate=False) # type: ignore[misc]
assert getattr(meta, attribute) == value
@pytest.mark.parametrize(
"attribute",
[
"supported_platforms",
"platforms",
"classifiers",
"provides_dist",
"obsoletes_dist",
"requires",
"provides",
"obsoletes",
],
)
def test_multi_value_unvalidated_attribute(self, attribute: str) -> None:
values = ["Not important", "Still not important"]
meta = metadata.Metadata.from_raw({attribute: values}, validate=False) # type: ignore[misc]
assert getattr(meta, attribute) == values
@pytest.mark.parametrize("version", ["1.0", "1.1", "1.2", "2.1", "2.2", "2.3"])
def test_valid_metadata_version(self, version: str) -> None:
meta = metadata.Metadata.from_raw({"metadata_version": version}, validate=False)
assert meta.metadata_version == version
@pytest.mark.parametrize("version", ["1.3", "2.0"])
def test_invalid_metadata_version(self, version: str) -> None:
meta = metadata.Metadata.from_raw({"metadata_version": version}, validate=False)
with pytest.raises(metadata.InvalidMetadata):
meta.metadata_version # noqa: B018
def test_valid_version(self) -> None:
version_str = "1.2.3"
meta = metadata.Metadata.from_raw({"version": version_str}, validate=False)
assert meta.version == version.parse(version_str)
def test_missing_version(self) -> None:
meta = metadata.Metadata.from_raw({}, validate=False)
with pytest.raises(metadata.InvalidMetadata) as exc_info:
meta.version # noqa: B018
assert exc_info.value.field == "version"
def test_invalid_version(self) -> None:
meta = metadata.Metadata.from_raw({"version": "a.b.c"}, validate=False)
self._invalid_with_cause(meta, "version", version.InvalidVersion)
def test_valid_summary(self) -> None:
summary = "Hello"
meta = metadata.Metadata.from_raw({"summary": summary}, validate=False)
assert meta.summary == summary
def test_invalid_summary(self) -> None:
meta = metadata.Metadata.from_raw(
{"summary": "Hello\n Again"}, validate=False
)
with pytest.raises(metadata.InvalidMetadata) as exc_info:
meta.summary # noqa: B018
assert exc_info.value.field == "summary"
def test_valid_name(self) -> None:
name = "Hello_World"
meta = metadata.Metadata.from_raw({"name": name}, validate=False)
assert meta.name == name
def test_invalid_name(self) -> None:
meta = metadata.Metadata.from_raw({"name": "-not-legal"}, validate=False)
self._invalid_with_cause(meta, "name", utils.InvalidName)
@pytest.mark.parametrize(
"content_type",
[
"text/plain",
"TEXT/PLAIN",
"text/x-rst",
"text/markdown",
"text/plain; charset=UTF-8",
"text/x-rst; charset=UTF-8",
"text/markdown; charset=UTF-8; variant=GFM",
"text/markdown; charset=UTF-8; variant=CommonMark",
"text/markdown; variant=GFM",
"text/markdown; variant=CommonMark",
],
)
def test_valid_description_content_type(self, content_type: str) -> None:
meta = metadata.Metadata.from_raw(
{"description_content_type": content_type}, validate=False
)
assert meta.description_content_type == content_type
@pytest.mark.parametrize(
"content_type",
[
"application/json",
"text/plain; charset=ascii",
"text/plain; charset=utf-8",
"text/markdown; variant=gfm",
"text/markdown; variant=commonmark",
],
)
def test_invalid_description_content_type(self, content_type: str) -> None:
meta = metadata.Metadata.from_raw(
{"description_content_type": content_type}, validate=False
)
with pytest.raises(metadata.InvalidMetadata):
meta.description_content_type # noqa: B018
def test_keywords(self) -> None:
keywords = ["hello", "world"]
meta = metadata.Metadata.from_raw({"keywords": keywords}, validate=False)
assert meta.keywords == keywords
def test_valid_project_urls(self) -> None:
urls = {
"Documentation": "https://example.com/BeagleVote",
"Bug Tracker": "http://bitbucket.org/tarek/distribute/issues/",
}
meta = metadata.Metadata.from_raw({"project_urls": urls}, validate=False)
assert meta.project_urls == urls
@pytest.mark.parametrize("specifier", [">=3", ">2.6,!=3.0.*,!=3.1.*", "~=2.6"])
def test_valid_requires_python(self, specifier: str) -> None:
expected = specifiers.SpecifierSet(specifier)
meta = metadata.Metadata.from_raw(
{"requires_python": specifier}, validate=False
)
assert meta.requires_python == expected
def test_invalid_requires_python(self) -> None:
meta = metadata.Metadata.from_raw(
{"requires_python": "NotReal"}, validate=False
)
self._invalid_with_cause(
meta,
"requires_python",
specifiers.InvalidSpecifier,
field="requires-python",
)
def test_requires_external(self) -> None:
externals = [
"C",
"libpng (>=1.5)",
'make; sys_platform != "win32"',
"libjpeg (>6b)",
]
meta = metadata.Metadata.from_raw(
{"requires_external": externals}, validate=False
)
assert meta.requires_external == externals
def test_valid_provides_extra(self) -> None:
extras = ["dev", "test"]
meta = metadata.Metadata.from_raw({"provides_extra": extras}, validate=False)
assert meta.provides_extra == extras
def test_invalid_provides_extra(self) -> None:
extras = ["pdf", "-Not-Valid", "ok"]
meta = metadata.Metadata.from_raw({"provides_extra": extras}, validate=False)
self._invalid_with_cause(
meta, "provides_extra", utils.InvalidName, field="provides-extra"
)
def test_valid_requires_dist(self) -> None:
requires = [
"pkginfo",
"PasteDeploy",
"zope.interface (>3.5.0)",
"pywin32 >1.0; sys_platform == 'win32'",
]
expected_requires = list(map(requirements.Requirement, requires))
meta = metadata.Metadata.from_raw({"requires_dist": requires}, validate=False)
assert meta.requires_dist == expected_requires
def test_invalid_requires_dist(self) -> None:
requires = ["pkginfo", "-not-real", "zope.interface (>3.5.0)"]
meta = metadata.Metadata.from_raw({"requires_dist": requires}, validate=False)
self._invalid_with_cause(
meta,
"requires_dist",
requirements.InvalidRequirement,
field="requires-dist",
)
def test_valid_dynamic(self) -> None:
dynamic = ["Keywords", "Home-Page", "Author"]
meta = metadata.Metadata.from_raw({"dynamic": dynamic}, validate=False)
assert meta.dynamic == [d.lower() for d in dynamic]
def test_invalid_dynamic_value(self) -> None:
dynamic = ["Keywords", "NotReal", "Author"]
meta = metadata.Metadata.from_raw({"dynamic": dynamic}, validate=False)
with pytest.raises(metadata.InvalidMetadata):
meta.dynamic # noqa: B018
@pytest.mark.parametrize("field_name", ["name", "version", "metadata-version"])
def test_disallowed_dynamic(self, field_name: str) -> None:
meta = metadata.Metadata.from_raw({"dynamic": [field_name]}, validate=False)
message = f"{field_name!r} is not allowed"
with pytest.raises(metadata.InvalidMetadata, match=message) as execinfo:
meta.dynamic # noqa: B018
# The name of the specific offending field should be used,
# not a list with all fields:
assert "[" not in str(execinfo.value)
@pytest.mark.parametrize(
"field_name",
sorted(metadata._RAW_TO_EMAIL_MAPPING.keys() - metadata._REQUIRED_ATTRS),
)
def test_optional_defaults_to_none(self, field_name: str) -> None:
meta = metadata.Metadata.from_raw({}, validate=False)
assert getattr(meta, field_name) is None
@pytest.mark.parametrize(
("license_expression", "expected"),
[
("MIT", "MIT"),
("mit", "MIT"),
("BSD-3-Clause", "BSD-3-Clause"),
("Bsd-3-clause", "BSD-3-Clause"),
(
"MIT AND (Apache-2.0 OR BSD-2-Clause)",
"MIT AND (Apache-2.0 OR BSD-2-Clause)",
),
(
"mit and (apache-2.0 or bsd-2-clause)",
"MIT AND (Apache-2.0 OR BSD-2-Clause)",
),
(
"MIT OR GPL-2.0-or-later OR (FSFUL AND BSD-2-Clause)",
"MIT OR GPL-2.0-or-later OR (FSFUL AND BSD-2-Clause)",
),
(
"GPL-3.0-only WITH Classpath-exception-2.0 OR BSD-3-Clause",
"GPL-3.0-only WITH Classpath-exception-2.0 OR BSD-3-Clause",
),
(
"LicenseRef-Special-License OR CC0-1.0 OR Unlicense",
"LicenseRef-Special-License OR CC0-1.0 OR Unlicense",
),
("mIt", "MIT"),
(" mIt ", "MIT"),
("mit or apache-2.0", "MIT OR Apache-2.0"),
("mit and apache-2.0", "MIT AND Apache-2.0"),
(
"gpl-2.0-or-later with bison-exception-2.2",
"GPL-2.0-or-later WITH Bison-exception-2.2",
),
(
"mit or apache-2.0 and (bsd-3-clause or mpl-2.0)",
"MIT OR Apache-2.0 AND (BSD-3-Clause OR MPL-2.0)",
),
("mit and (apache-2.0+ or mpl-2.0+)", "MIT AND (Apache-2.0+ OR MPL-2.0+)"),
(
"mit and ( apache-2.0+ or mpl-2.0+ )",
"MIT AND (Apache-2.0+ OR MPL-2.0+)",
),
# Valid non-SPDX values
("LicenseRef-Public-Domain", "LicenseRef-Public-Domain"),
("licenseref-public-domain", "LicenseRef-public-domain"),
("licenseref-proprietary", "LicenseRef-proprietary"),
("LicenseRef-Proprietary", "LicenseRef-Proprietary"),
("LicenseRef-Beerware-4.2", "LicenseRef-Beerware-4.2"),
("licenseref-beerware-4.2", "LicenseRef-beerware-4.2"),
(
"(LicenseRef-Special-License OR LicenseRef-OtherLicense) OR Unlicense",
"(LicenseRef-Special-License OR LicenseRef-OtherLicense) OR Unlicense",
),
(
"(LicenseRef-Special-License OR licenseref-OtherLicense) OR unlicense",
"(LicenseRef-Special-License OR LicenseRef-OtherLicense) OR Unlicense",
),
# we don't canonicalize redundant parens, instead leaving them as-is
# in the license expression.
("(MIT)", "(MIT)"),
("((MIT))", "((MIT))"),
("(( MIT ))", "((MIT))"),
("((MIT AND (MIT)))", "((MIT AND (MIT)))"),
],
)
def test_valid_license_expression(
self, license_expression: str, expected: str
) -> None:
meta = metadata.Metadata.from_raw(
{"license_expression": license_expression}, validate=False
)
assert meta.license_expression == expected
@pytest.mark.parametrize(
"license_expression",
[
"",
"Use-it-after-midnight",
"LicenseRef-License with spaces",
"LicenseRef-License_with_underscores",
"or",
"and",
"with",
"mit or",
"mit and",
"mit with",
"or mit",
"and mit",
"with mit",
"(mit",
"mit)",
") mit",
"mit (",
"mit or or apache-2.0",
# Missing an operator before `(`.
"mit or apache-2.0 (bsd-3-clause and MPL-2.0)",
# "2-BSD-Clause is not a valid license.
"Apache-2.0 OR 2-BSD-Clause",
# Empty parenthesis.
"()",
"( ) or mit",
"mit and ( )",
"( ) or mit and ( )",
"( ) with ( ) or mit",
"mit with ( ) with ( ) or mit",
],
)
def test_invalid_license_expression(self, license_expression: str) -> None:
meta = metadata.Metadata.from_raw(
{"license_expression": license_expression}, validate=False
)
with pytest.raises(metadata.InvalidMetadata):
meta.license_expression # noqa: B018
@pytest.mark.parametrize(
"license_files",
[
[],
["licenses/LICENSE.MIT", "licenses/LICENSE.CC0"],
["LICENSE"],
],
)
def test_valid_license_files(self, license_files: list[str]) -> None:
meta = metadata.Metadata.from_raw(
{"license_files": license_files}, validate=False
)
assert meta.license_files == license_files
@pytest.mark.parametrize(
"license_files",
[
# Can't escape out of the project's directory.
["../LICENSE"],
["./../LICENSE"],
# Paths should be resolved.
["licenses/../LICENSE"],
# Absolute paths are not allowed.
["/licenses/LICENSE"],
# Paths must be valid
# (i.e. glob pattern didn't escape out of pyproject.toml.)
["licenses/*"],
# Paths must use / delimiter
["licenses\\LICENSE"],
],
)
def test_invalid_license_files(self, license_files: list[str]) -> None:
meta = metadata.Metadata.from_raw(
{"license_files": license_files}, validate=False
)
with pytest.raises(metadata.InvalidMetadata):
meta.license_files # noqa: B018
@pytest.mark.parametrize("key", ["import_namespaces", "import_names"])
def test_valid_import_names(self, key: str) -> None:
import_names = [
"packaging",
"packaging.metadata",
"_utils ; private",
"_stuff;private",
]
meta = metadata.Metadata.from_raw({key: import_names}, validate=False) # type: ignore[misc]
assert getattr(meta, key) == import_names
@pytest.mark.parametrize("key", ["import_namespaces", "import_names"])
@pytest.mark.parametrize(
"name", ["not-valid", "still.not-valid", "stuff;", "stuff; extra"]
)
def test_invalid_import_names_identifier(self, key: str, name: str) -> None:
meta = metadata.Metadata.from_raw({key: [name]}, validate=False) # type: ignore[misc]
with pytest.raises(metadata.InvalidMetadata):
getattr(meta, key)
@pytest.mark.parametrize("key", ["import_namespaces", "import_names"])
def test_invalid_import_names_keyword(self, key: str) -> None:
import_names = ["class"]
meta = metadata.Metadata.from_raw({key: import_names}, validate=False) # type: ignore[misc]
with pytest.raises(metadata.InvalidMetadata):
getattr(meta, key)
class TestMetadataWriting:
def test_write_metadata(self) -> None:
meta = metadata.Metadata.from_raw(_RAW_EXAMPLE)
written = meta.as_rfc822().as_string()
assert (
written == "metadata-version: 2.5\nname: packaging\nversion: 2023.0.0\n\n"
)
def test_write_metadata_with_description(self) -> None:
# Intentionally out of order to make sure it is written in order
meta = metadata.Metadata.from_raw(
{
"version": "1.2.3",
"name": "Hello",
"description": "Hello\n\nWorld👋",
"metadata_version": "2.3",
}
)
written = meta.as_rfc822().as_string()
assert (
written == "metadata-version: 2.3\nname: Hello\n"
"version: 1.2.3\n\nHello\n\nWorld👋"
)
written_bytes = meta.as_rfc822().as_bytes()
assert (
written_bytes
== "metadata-version: 2.3\nname: Hello\n"
"version: 1.2.3\n\nHello\n\nWorld👋".encode()
)
def test_multiline_license(self) -> None:
meta = metadata.Metadata.from_raw(
{
"version": "1.2.3",
"name": "packaging",
"license": "Hello\nWorld🐍",
"metadata_version": "2.3",
}
)
written = meta.as_rfc822().as_string()
assert (
written == "metadata-version: 2.3\nname: packaging\nversion: 1.2.3"
"\nlicense: Hello\n World🐍\n\n"
)
written_bytes = meta.as_rfc822().as_bytes()
assert (
written_bytes
== "metadata-version: 2.3\nname: packaging\nversion: 1.2.3"
"\nlicense: Hello\n World🐍\n\n".encode()
)
def test_large(self) -> None:
meta = metadata.Metadata.from_raw(
{
"author": "Example!",
"author_email": "Unknown ",
"classifiers": [
"Development Status :: 4 - Beta",
"Programming Language :: Python",
],
"description": "some readme 👋\n",
"description_content_type": "text/markdown",
"keywords": ["trampolim", "is", "interesting"],
"license": "some license text",
"maintainer_email": "Other Example ",
"metadata_version": "2.1",
"name": "full_metadata",
"project_urls": {
"homepage": "example.com",
"documentation": "readthedocs.org",
"repository": "github.com/some/repo",
"changelog": "github.com/some/repo/blob/master/CHANGELOG.rst",
},
"provides_extra": ["test"],
"requires_dist": [
"dependency1",
"dependency2>1.0.0",
"dependency3[extra]",
'dependency4; os_name != "nt"',
'dependency5[other-extra]>1.0; os_name == "nt"',
'test_dependency; extra == "test"',
'test_dependency[test_extra]; extra == "test"',
"test_dependency[test_extra2]>3.0; "
'os_name == "nt" and extra == "test"',
],
"requires_python": ">=3.8",
"summary": "A package with all the metadata :)",
"version": "3.2.1",
}
)
core_metadata = meta.as_rfc822()
assert core_metadata.items() == [
("metadata-version", "2.1"),
("name", "full_metadata"),
("version", "3.2.1"),
("summary", "A package with all the metadata :)"),
("description-content-type", "text/markdown"),
("keywords", "trampolim,is,interesting"),
("author", "Example!"),
("author-email", "Unknown "),
("maintainer-email", "Other Example "),
("license", "some license text"),
("classifier", "Development Status :: 4 - Beta"),
("classifier", "Programming Language :: Python"),
("requires-dist", "dependency1"),
("requires-dist", "dependency2>1.0.0"),
("requires-dist", "dependency3[extra]"),
("requires-dist", 'dependency4; os_name != "nt"'),
("requires-dist", 'dependency5[other-extra]>1.0; os_name == "nt"'),
("requires-dist", 'test_dependency; extra == "test"'),
("requires-dist", 'test_dependency[test_extra]; extra == "test"'),
(
"requires-dist",
'test_dependency[test_extra2]>3.0; os_name == "nt" and extra == "test"',
),
("requires-python", ">=3.8"),
("project-url", "homepage, example.com"),
("project-url", "documentation, readthedocs.org"),
("project-url", "repository, github.com/some/repo"),
(
"project-url",
"changelog, github.com/some/repo/blob/master/CHANGELOG.rst",
),
("provides-extra", "test"),
]
assert core_metadata.get_payload() == "some readme 👋\n"
def test_modern_license(self) -> None:
meta = metadata.Metadata.from_raw(
{
"metadata_version": "2.4",
"name": "full_metadata",
"version": "3.2.1",
"license_expression": "MIT",
"license_files": ["LICENSE.txt", "LICENSE"],
}
)
core_metadata = meta.as_rfc822()
assert core_metadata.items() == [
("metadata-version", "2.4"),
("name", "full_metadata"),
("version", "3.2.1"),
("license-expression", "MIT"),
("license-file", "LICENSE.txt"),
("license-file", "LICENSE"),
]
assert core_metadata.get_payload() is None
def test__import_names(self) -> None:
meta = metadata.Metadata.from_raw(
{
"metadata_version": "2.5",
"name": "full_metadata",
"version": "3.2.1",
"import_names": ["one", "two"],
"import_namespaces": ["three"],
}
)
core_metadata = meta.as_rfc822()
assert core_metadata.items() == [
("metadata-version", "2.5"),
("name", "full_metadata"),
("version", "3.2.1"),
("import-name", "one"),
("import-name", "two"),
("import-namespace", "three"),
]
assert core_metadata.get_payload() is None
def test_empty_import_names(self) -> None:
meta = metadata.Metadata.from_raw(
{
"metadata_version": "2.5",
"name": "full_metadata",
"version": "3.2.1",
"import_names": [],
}
)
core_metadata = meta.as_rfc822()
assert core_metadata.items() == [
("metadata-version", "2.5"),
("name", "full_metadata"),
("version", "3.2.1"),
("import-name", ""),
]
assert core_metadata.get_payload() is None
@pytest.mark.parametrize(
("items", "data"),
[
pytest.param(
[],
"",
id="empty",
),
pytest.param(
[
("Foo", "Bar"),
],
"Foo: Bar\n",
id="simple",
),
pytest.param(
[
("Foo", "Bar"),
("Foo2", "Bar2"),
],
"""\
Foo: Bar
Foo2: Bar2
""",
id="multiple",
),
pytest.param(
[
("Foo", "Unicøde"),
],
"Foo: Unicøde\n",
id="unicode",
),
pytest.param(
[
("Foo", "🕵️"),
],
"Foo: 🕵️\n",
id="emoji",
),
pytest.param(
[
("Item", None),
],
"",
id="none",
),
pytest.param(
[
("ItemA", "ValueA"),
("ItemB", "ValueB"),
("ItemC", "ValueC"),
],
"""\
ItemA: ValueA
ItemB: ValueB
ItemC: ValueC
""",
id="order 1",
),
pytest.param(
[
("ItemB", "ValueB"),
("ItemC", "ValueC"),
("ItemA", "ValueA"),
],
"""\
ItemB: ValueB
ItemC: ValueC
ItemA: ValueA
""",
id="order 2",
),
pytest.param(
[
("ItemA", "ValueA1"),
("ItemB", "ValueB"),
("ItemC", "ValueC"),
("ItemA", "ValueA2"),
],
"""\
ItemA: ValueA1
ItemB: ValueB
ItemC: ValueC
ItemA: ValueA2
""",
id="multiple keys",
),
pytest.param(
[
("ItemA", "ValueA"),
("ItemB", "ValueB1\nValueB2\nValueB3"),
("ItemC", "ValueC"),
],
"""\
ItemA: ValueA
ItemB: ValueB1
ValueB2
ValueB3
ItemC: ValueC
""",
id="multiline",
),
],
)
def test_headers(self, items: list[tuple[str, None | str]], data: str) -> None:
message = metadata.RFC822Message()
for name, value in items:
if value:
message[name] = value
data = textwrap.dedent(data) + "\n"
assert str(message) == data
assert bytes(message) == data.encode()
assert email.message_from_string(str(message)).items() == [
(a, "\n ".join(b.splitlines())) for a, b in items if b is not None
]
def test_body(self) -> None:
message = metadata.RFC822Message()
message["ItemA"] = "ValueA"
message["ItemB"] = "ValueB"
message["ItemC"] = "ValueC"
body = inspect.cleandoc(
"""
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris
congue semper fermentum. Nunc vitae tempor ante. Aenean aliquet
posuere lacus non faucibus. In porttitor congue luctus. Vivamus eu
dignissim orci. Donec egestas mi ac ipsum volutpat, vel elementum
sapien consectetur. Praesent dictum finibus fringilla. Sed vel
feugiat leo. Nulla a pharetra augue, at tristique metus.
Aliquam fermentum elit at risus sagittis, vel pretium augue congue.
Donec leo risus, faucibus vel posuere efficitur, feugiat ut leo.
Aliquam vestibulum vel dolor id elementum. Ut bibendum nunc interdum
neque interdum, vel tincidunt lacus blandit. Ut volutpat
sollicitudin dapibus. Integer vitae lacinia ex, eget finibus nulla.
Donec sit amet ante in neque pulvinar faucibus sed nec justo. Fusce
hendrerit massa libero, sit amet pulvinar magna tempor quis. ø
"""
)
headers = inspect.cleandoc(
"""
ItemA: ValueA
ItemB: ValueB
ItemC: ValueC
"""
)
full = f"{headers}\n\n{body}"
message.set_payload(textwrap.dedent(body))
assert str(message) == full
new_message = email.message_from_string(str(message))
assert new_message.items() == message.items()
assert new_message.get_payload() == message.get_payload()
assert bytes(message) == full.encode("utf-8")
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1768936045.8193686
packaging-26.0/tests/test_musllinux.py 0000644 0000000 0000000 00000005543 15133751156 015144 0 ustar 00 from __future__ import annotations
import collections
import pathlib
import subprocess
import typing
import pretend
import pytest
from packaging import _musllinux
from packaging._musllinux import _get_musl_version, _MuslVersion, _parse_musl_version
if typing.TYPE_CHECKING:
from collections.abc import Generator
MUSL_AMD64 = "musl libc (x86_64)\nVersion 1.2.2\n"
MUSL_I386 = "musl libc (i386)\nVersion 1.2.1\n"
MUSL_AARCH64 = "musl libc (aarch64)\nVersion 1.1.24\n"
MUSL_INVALID = "musl libc (invalid)\n"
MUSL_UNKNOWN = "musl libc (unknown)\nVersion unknown\n"
MUSL_DIR = pathlib.Path(__file__).with_name("musllinux").resolve()
BIN_GLIBC_X86_64 = MUSL_DIR.joinpath("glibc-x86_64")
BIN_MUSL_X86_64 = MUSL_DIR.joinpath("musl-x86_64")
BIN_MUSL_I386 = MUSL_DIR.joinpath("musl-i386")
BIN_MUSL_AARCH64 = MUSL_DIR.joinpath("musl-aarch64")
LD_MUSL_X86_64 = "/lib/ld-musl-x86_64.so.1"
LD_MUSL_I386 = "/lib/ld-musl-i386.so.1"
LD_MUSL_AARCH64 = "/lib/ld-musl-aarch64.so.1"
@pytest.fixture(autouse=True)
def clear_lru_cache() -> Generator[None, None, None]:
yield
_get_musl_version.cache_clear()
@pytest.mark.parametrize(
("output", "version"),
[
(MUSL_AMD64, _MuslVersion(1, 2)),
(MUSL_I386, _MuslVersion(1, 2)),
(MUSL_AARCH64, _MuslVersion(1, 1)),
(MUSL_INVALID, None),
(MUSL_UNKNOWN, None),
],
ids=["amd64-1.2.2", "i386-1.2.1", "aarch64-1.1.24", "invalid", "unknown"],
)
def test_parse_musl_version(output: str, version: _MuslVersion | None) -> None:
assert _parse_musl_version(output) == version
@pytest.mark.parametrize(
("executable", "output", "version", "ld_musl"),
[
(MUSL_DIR.joinpath("does-not-exist"), "error", None, None),
(BIN_GLIBC_X86_64, "error", None, None),
(BIN_MUSL_X86_64, MUSL_AMD64, _MuslVersion(1, 2), LD_MUSL_X86_64),
(BIN_MUSL_I386, MUSL_I386, _MuslVersion(1, 2), LD_MUSL_I386),
(BIN_MUSL_AARCH64, MUSL_AARCH64, _MuslVersion(1, 1), LD_MUSL_AARCH64),
],
ids=["does-not-exist", "glibc", "x86_64", "i386", "aarch64"],
)
def test_get_musl_version(
monkeypatch: pytest.MonkeyPatch,
executable: pathlib.Path,
output: str,
version: _MuslVersion | None,
ld_musl: str | None,
) -> None:
def mock_run(*args: object, **kwargs: object) -> tuple[object, ...]:
return collections.namedtuple("Proc", "stderr")(output)
run_recorder = pretend.call_recorder(mock_run)
monkeypatch.setattr(_musllinux.subprocess, "run", run_recorder) # type: ignore[attr-defined]
assert _get_musl_version(str(executable)) == version
if ld_musl is not None:
expected_calls = [
pretend.call(
[ld_musl],
check=False,
stderr=subprocess.PIPE,
text=True,
)
]
else:
expected_calls = []
assert run_recorder.calls == expected_calls
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1768936045.8193686
packaging-26.0/tests/test_pylock.py 0000644 0000000 0000000 00000040530 15133751156 014400 0 ustar 00 from __future__ import annotations
import datetime
import sys
from pathlib import Path
from typing import Any
import pytest
import tomli_w
from packaging.markers import Marker
from packaging.pylock import (
Package,
PackageDirectory,
PackageVcs,
PackageWheel,
Pylock,
PylockUnsupportedVersionError,
PylockValidationError,
is_valid_pylock_path,
)
from packaging.specifiers import SpecifierSet
from packaging.utils import NormalizedName
from packaging.version import Version
if sys.version_info >= (3, 11):
import tomllib
else:
import tomli as tomllib
@pytest.mark.parametrize(
("file_name", "valid"),
[
("pylock.toml", True),
("pylock.spam.toml", True),
("pylock.json", False),
("pylock..toml", False),
],
)
def test_pylock_file_name(file_name: str, valid: bool) -> None:
assert is_valid_pylock_path(Path(file_name)) is valid
def test_toml_roundtrip() -> None:
pep751_example = (
Path(__file__).parent / "pylock" / "pylock.spec-example.toml"
).read_text()
pylock_dict = tomllib.loads(pep751_example)
pylock = Pylock.from_dict(pylock_dict)
# Check that the roundrip via Pylock dataclasses produces the same TOML
# output, modulo TOML serialization differences.
assert tomli_w.dumps(pylock.to_dict()) == tomli_w.dumps(pylock_dict)
@pytest.mark.parametrize("version", ["1.0", "1.1"])
def test_pylock_version(version: str) -> None:
data = {
"lock-version": version,
"created-by": "pip",
"packages": [],
}
Pylock.from_dict(data)
@pytest.mark.parametrize("version", ["0.9", "2", "2.0", "2.1"])
def test_pylock_unsupported_version(version: str) -> None:
data = {
"lock-version": version,
"created-by": "pip",
"packages": [],
}
with pytest.raises(PylockUnsupportedVersionError):
Pylock.from_dict(data)
def test_pylock_invalid_version() -> None:
data = {
"lock-version": "2.x",
"created-by": "pip",
"packages": [],
}
with pytest.raises(PylockValidationError) as exc_info:
Pylock.from_dict(data)
assert str(exc_info.value) == "Invalid version: '2.x' in 'lock-version'"
def test_pylock_unexpected_type() -> None:
data = {
"lock-version": 1.0,
"created-by": "pip",
"packages": [],
}
with pytest.raises(PylockValidationError) as exc_info:
Pylock.from_dict(data)
assert str(exc_info.value) == (
"Unexpected type float (expected str) in 'lock-version'"
)
def test_pylock_missing_version() -> None:
data = {
"created-by": "pip",
"packages": [],
}
with pytest.raises(PylockValidationError) as exc_info:
Pylock.from_dict(data)
assert str(exc_info.value) == "Missing required value in 'lock-version'"
def test_pylock_missing_created_by() -> None:
data = {
"lock-version": "1.0",
"packages": [],
}
with pytest.raises(PylockValidationError) as exc_info:
Pylock.from_dict(data)
assert str(exc_info.value) == "Missing required value in 'created-by'"
def test_pylock_missing_packages() -> None:
data = {
"lock-version": "1.0",
"created-by": "uv",
}
with pytest.raises(PylockValidationError) as exc_info:
Pylock.from_dict(data)
assert str(exc_info.value) == "Missing required value in 'packages'"
def test_pylock_packages_without_dist() -> None:
data = {
"lock-version": "1.0",
"created-by": "pip",
"packages": [{"name": "example", "version": "1.0"}],
}
with pytest.raises(PylockValidationError) as exc_info:
Pylock.from_dict(data)
assert str(exc_info.value) == (
"Exactly one of vcs, directory, archive must be set "
"if sdist and wheels are not set "
"in 'packages[0]'"
)
def test_pylock_packages_with_dist_and_archive() -> None:
data = {
"lock-version": "1.0",
"created-by": "pip",
"packages": [
{
"name": "example",
"version": "1.0",
"archive": {
"path": "example.tar.gz",
"hashes": {"sha256": "f" * 40},
},
"sdist": {
"path": "example.tar.gz",
"hashes": {"sha256": "f" * 40},
},
}
],
}
with pytest.raises(PylockValidationError) as exc_info:
Pylock.from_dict(data)
assert str(exc_info.value) == (
"None of vcs, directory, archive must be set "
"if sdist or wheels are set "
"in 'packages[0]'"
)
def test_pylock_packages_with_archive_directory_and_vcs() -> None:
data = {
"lock-version": "1.0",
"created-by": "pip",
"packages": [
{
"name": "example",
"version": "1.0",
"archive": {
"path": "example.tar.gz",
"hashes": {"sha256": "f" * 40},
},
"vcs": {
"type": "git",
"url": "https://githhub/pypa/packaging",
"commit-id": "...",
},
"directory": {
"path": ".",
"editable": False,
},
}
],
}
with pytest.raises(PylockValidationError) as exc_info:
Pylock.from_dict(data)
assert str(exc_info.value) == (
"Exactly one of vcs, directory, archive must be set "
"if sdist and wheels are not set "
"in 'packages[0]'"
)
def test_pylock_basic_package() -> None:
data = {
"lock-version": "1.0",
"created-by": "pip",
"requires-python": ">=3.10",
"environments": ['os_name == "posix"'],
"packages": [
{
"name": "example",
"version": "1.0",
"marker": 'os_name == "posix"',
"requires-python": "!=3.10.1,>=3.10",
"directory": {
"path": ".",
"editable": False,
},
}
],
}
pylock = Pylock.from_dict(data)
assert pylock.environments == [Marker('os_name == "posix"')]
package = pylock.packages[0]
assert package.version == Version("1.0")
assert package.marker == Marker('os_name == "posix"')
assert package.requires_python == SpecifierSet(">=3.10, !=3.10.1")
assert pylock.to_dict() == data
def test_pylock_vcs_package() -> None:
data = {
"lock-version": "1.0",
"created-by": "pip",
"packages": [
{
"name": "packaging",
"vcs": {
"type": "git",
"url": "https://githhub/pypa/packaging",
"commit-id": "...",
},
}
],
}
pylock = Pylock.from_dict(data)
assert pylock.to_dict() == data
def test_pylock_invalid_archive() -> None:
data = {
"lock-version": "1.0",
"created-by": "pip",
"requires-python": ">=3.10",
"environments": ['os_name == "posix"'],
"packages": [
{
"name": "example",
"archive": {
# "path": "example.tar.gz",
"hashes": {"sha256": "f" * 40},
},
}
],
}
with pytest.raises(PylockValidationError) as exc_info:
Pylock.from_dict(data)
assert str(exc_info.value) == (
"path or url must be provided in 'packages[0].archive'"
)
def test_pylock_invalid_vcs() -> None:
with pytest.raises(PylockValidationError) as exc_info:
PackageVcs._from_dict({"type": "git", "commit-id": "f" * 40})
assert str(exc_info.value) == "path or url must be provided"
def test_pylock_invalid_wheel() -> None:
data = {
"lock-version": "1.0",
"created-by": "pip",
"requires-python": ">=3.10",
"environments": ['os_name == "posix"'],
"packages": [
{
"name": "example",
"wheels": [
{
"name": "example-1.0-py3-none-any.whl",
"path": "./example-1.0-py3-none-any.whl",
# Purposefully no "hashes" key.
}
],
}
],
}
with pytest.raises(PylockValidationError) as exc_info:
Pylock.from_dict(data)
assert str(exc_info.value) == (
"Missing required value in 'packages[0].wheels[0].hashes'"
)
def test_pylock_invalid_environments() -> None:
data = {
"lock-version": "1.0",
"created-by": "pip",
"environments": [
'os_name == "posix"',
'invalid_marker == "..."',
],
"packages": [],
}
with pytest.raises(PylockValidationError) as exc_info:
Pylock.from_dict(data)
assert str(exc_info.value) == (
"Expected a marker variable or quoted string\n"
' invalid_marker == "..."\n'
" ^ "
"in 'environments[1]'"
)
def test_pylock_invalid_environments_type() -> None:
data = {
"lock-version": "1.0",
"created-by": "pip",
"environments": [
'os_name == "posix"',
1,
],
"packages": [],
}
with pytest.raises(PylockValidationError) as exc_info:
Pylock.from_dict(data)
assert str(exc_info.value) == (
"Unexpected type int (expected str) in 'environments[1]'"
)
def test_pylock_extras_and_groups() -> None:
data = {
"lock-version": "1.0",
"created-by": "pip",
"extras": ["feat1", "feat2"],
"dependency-groups": ["dev", "docs"],
"default-groups": ["dev"],
"packages": [],
}
pylock = Pylock.from_dict(data)
assert pylock.extras == ["feat1", "feat2"]
assert pylock.dependency_groups == ["dev", "docs"]
assert pylock.default_groups == ["dev"]
def test_pylock_tool() -> None:
data = {
"lock-version": "1.0",
"created-by": "pip",
"packages": [
{
"name": "example",
"sdist": {
"name": "example-1.0.tar.gz",
"path": "./example-1.0.tar.gz",
"upload-time": datetime.datetime(
2023, 10, 1, 0, 0, tzinfo=datetime.timezone.utc
),
"hashes": {"sha256": "f" * 40},
},
"tool": {"pip": {"foo": "bar"}},
}
],
"tool": {"pip": {"version": "25.2"}},
}
pylock = Pylock.from_dict(data)
assert pylock.tool == {"pip": {"version": "25.2"}}
package = pylock.packages[0]
assert package.tool == {"pip": {"foo": "bar"}}
def test_pylock_package_not_a_table() -> None:
data = {
"lock-version": "1.0",
"created-by": "pip",
"packages": ["example"],
}
with pytest.raises(PylockValidationError) as exc_info:
Pylock.from_dict(data)
assert str(exc_info.value) == (
"Unexpected type str (expected Mapping) in 'packages[0]'"
)
@pytest.mark.parametrize(
("hashes", "expected_error"),
[
(
{
"sha256": "f" * 40,
"md5": 1,
},
"Hash values must be strings in 'hashes'",
),
(
{},
"At least one hash must be provided in 'hashes'",
),
(
"sha256:...",
"Unexpected type str (expected Mapping) in 'hashes'",
),
],
)
def test_hash_validation(hashes: dict[str, Any], expected_error: str) -> None:
with pytest.raises(PylockValidationError) as exc_info:
PackageWheel._from_dict(
dict(
name="example-1.0-py3-none-any.whl",
upload_time=None,
url="https://example.com/example-1.0-py3-none-any.whl",
path=None,
size=None,
hashes=hashes,
)
)
assert str(exc_info.value) == expected_error
def test_package_name_validation() -> None:
with pytest.raises(PylockValidationError) as exc_info:
Package._from_dict({"name": "Example"})
assert str(exc_info.value) == "Name 'Example' is not normalized in 'name'"
def test_extras_name_validation() -> None:
with pytest.raises(PylockValidationError) as exc_info:
Pylock.from_dict(
{
"lock-version": "1.0",
"created-by": "pip",
"extras": ["extra", "Feature"],
"packages": [],
}
)
assert str(exc_info.value) == "Name 'Feature' is not normalized in 'extras[1]'"
def test_is_direct() -> None:
direct_package = Package(
name=NormalizedName("example"),
directory=PackageDirectory(path="."),
)
assert direct_package.is_direct
wheel_package = Package(
name=NormalizedName("example"),
wheels=[
PackageWheel(
url="https://example.com/example-1.0-py3-none-any.whl",
hashes={"sha256": "f" * 40},
)
],
)
assert not wheel_package.is_direct
def test_validate() -> None:
pylock = Pylock(
lock_version=Version("1.0"),
created_by="some_tool",
packages=[
Package(
name=NormalizedName("example-package"),
version=Version("1.0.0"),
wheels=[
PackageWheel(
url="https://example.com/example_package-1.0.0-py3-none-any.whl",
hashes={"sha256": "0fd.."},
)
],
)
],
)
pylock.validate() # Should not raise any exceptions
pylock = Pylock(
lock_version=Version("1.0"),
created_by="some_tool",
packages=[
Package(
name=NormalizedName("example_package"), # not normalized
version=Version("1.0.0"),
wheels=[
PackageWheel(
url="https://example.com/example_package-1.0.0-py3-none-any.whl",
hashes={"sha256": "0fd.."},
)
],
)
],
)
with pytest.raises(PylockValidationError) as exc_info:
pylock.validate()
assert (
str(exc_info.value)
== "Name 'example_package' is not normalized in 'packages[0].name'"
)
def test_validate_sequence_of_str() -> None:
pylock = Pylock(
lock_version=Version("1.0"),
created_by="some_tool",
packages=[],
dependency_groups="abc", # should be a sequence of str
)
with pytest.raises(PylockValidationError) as exc_info:
pylock.validate()
assert str(exc_info.value) == (
"Unexpected type str (expected Sequence) in 'dependency-groups'"
)
def test_validate_attestation_identity_missing_kind() -> None:
data = {
"lock-version": "1.0",
"created-by": "pip",
"packages": [
{
"name": "example",
"version": "1.0",
"directory": {
"path": ".",
},
"attestation-identities": [
{
# missing "kind" field
"value": "some-value",
}
],
}
],
}
with pytest.raises(PylockValidationError) as exc_info:
Pylock.from_dict(data)
assert str(exc_info.value) == (
"Missing required value in 'packages[0].attestation-identities[0].kind'"
)
def test_validate_attestation_identity_invalid_kind() -> None:
data = {
"lock-version": "1.0",
"created-by": "pip",
"packages": [
{
"name": "example",
"version": "1.0",
"directory": {
"path": ".",
},
"attestation-identities": [
{
"kind": 123,
"value": "some-value",
}
],
}
],
}
with pytest.raises(PylockValidationError) as exc_info:
Pylock.from_dict(data)
assert str(exc_info.value) == (
"Unexpected type int (expected str) "
"in 'packages[0].attestation-identities[0].kind'"
)
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1768936045.8193686
packaging-26.0/tests/test_requirements.py 0000644 0000000 0000000 00000051542 15133751156 015627 0 ustar 00 # This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import annotations
import pytest
from packaging.markers import Marker
from packaging.requirements import InvalidRequirement, Requirement
from packaging.specifiers import SpecifierSet
EQUAL_DEPENDENCIES = [
("packaging>20.1", "packaging>20.1"),
(
'requests[security, tests]>=2.8.1,==2.8.*;python_version<"2.7"',
'requests [security,tests] >= 2.8.1, == 2.8.* ; python_version < "2.7"',
),
(
'importlib-metadata; python_version<"3.8"',
"importlib-metadata; python_version<'3.8'",
),
(
'appdirs>=1.4.4,<2; os_name=="posix" and extra=="testing"',
"appdirs>=1.4.4,<2; os_name == 'posix' and extra == 'testing'",
),
]
EQUIVALENT_DEPENDENCIES = [
("scikit-learn==1.0.1", "scikit_learn==1.0.1"),
]
DIFFERENT_DEPENDENCIES = [
("package_one", "package_two"),
("packaging>20.1", "packaging>=20.1"),
("packaging>20.1", "packaging>21.1"),
("packaging>20.1", "package>20.1"),
(
'requests[security,tests]>=2.8.1,==2.8.*;python_version<"2.7"',
'requests [security,tests] >= 2.8.1 ; python_version < "2.7"',
),
(
'importlib-metadata; python_version<"3.8"',
"importlib-metadata; python_version<'3.7'",
),
(
'appdirs>=1.4.4,<2; os_name=="posix" and extra=="testing"',
"appdirs>=1.4.4,<2; os_name == 'posix' and extra == 'docs'",
),
]
@pytest.mark.parametrize(
"name",
[
"package",
"pAcKaGe",
"Package",
"foo-bar.quux_bAz",
"installer",
"android12",
],
)
@pytest.mark.parametrize(
"extras",
[
set(),
{"a"},
{"a", "b"},
{"a", "B", "CDEF123"},
],
)
@pytest.mark.parametrize(
("url", "specifier"),
[
(None, ""),
("https://example.com/packagename.zip", ""),
("ssh://user:pass%20word@example.com/packagename.zip", ""),
("https://example.com/name;v=1.1/?query=foo&bar=baz#blah", ""),
("git+ssh://git.example.com/MyProject", ""),
("git+ssh://git@github.com:pypa/packaging.git", ""),
("git+https://git.example.com/MyProject.git@master", ""),
("git+https://git.example.com/MyProject.git@v1.0", ""),
("git+https://git.example.com/MyProject.git@refs/pull/123/head", ""),
("gopher:/foo/com", ""),
(None, "==={ws}arbitrarystring"),
(None, "({ws}==={ws}arbitrarystring{ws})"),
(None, "=={ws}1.0"),
(None, "({ws}=={ws}1.0{ws})"),
(None, "=={ws}1.0-alpha"),
(None, "<={ws}1!3.0.0.rc2"),
(None, ">{ws}2.2{ws},{ws}<{ws}3"),
(None, "(>{ws}2.2{ws},{ws}<{ws}3)"),
],
)
@pytest.mark.parametrize(
"marker",
[
None,
"python_version{ws}>={ws}'3.3'",
'({ws}python_version{ws}>={ws}"3.4"{ws}){ws}and extra{ws}=={ws}"oursql"',
(
"sys_platform{ws}!={ws}'linux' and(os_name{ws}=={ws}'linux' or "
"python_version{ws}>={ws}'3.3'{ws}){ws}"
),
],
)
@pytest.mark.parametrize("whitespace", ["", " ", "\t"])
def test_basic_valid_requirement_parsing(
name: str,
extras: set[str],
specifier: str,
url: str | None,
marker: str,
whitespace: str,
) -> None:
# GIVEN
parts = [name]
if extras:
parts.append("[")
parts.append("{ws},{ws}".format(ws=whitespace).join(sorted(extras)))
parts.append("]")
if specifier:
parts.append(specifier.format(ws=whitespace))
if url is not None:
parts.append("@")
parts.append(url.format(ws=whitespace))
if marker is not None:
if url is not None:
parts.append(" ;")
else:
parts.append(";")
parts.append(marker.format(ws=whitespace))
to_parse = whitespace.join(parts)
# WHEN
req = Requirement(to_parse)
# THEN
assert req.name == name
assert req.extras == extras
assert req.url == url
assert req.specifier == specifier.format(ws="").strip("()")
assert req.marker == (Marker(marker.format(ws="")) if marker else None)
@pytest.mark.parametrize(
("input_req", "norm_req"),
[
(
'mariadb>=1.0.1; extra == "mariadb_connector"',
'mariadb>=1.0.1; extra == "mariadb-connector"',
),
(
'mariadb>=1.0.1; python_version >= "3" and extra == "mariadb_connector"',
'mariadb>=1.0.1; python_version >= "3" and extra == "mariadb-connector"',
),
],
)
def test_normalized_requirements(input_req: str, norm_req: str) -> None:
req = Requirement(input_req)
assert str(req) == norm_req
class TestRequirementParsing:
@pytest.mark.parametrize(
"marker",
[
"python_implementation == ''",
"platform_python_implementation == ''",
"os.name == 'linux'",
"os_name == 'linux'",
"'8' in platform.version",
"'8' not in platform.version",
],
)
def test_valid_marker(self, marker: str) -> None:
# GIVEN
to_parse = f"name; {marker}"
# WHEN
Requirement(to_parse)
@pytest.mark.parametrize(
"url",
[
"file:///absolute/path",
"file://.",
"file:.",
"file:/.",
],
)
def test_file_url(self, url: str) -> None:
# GIVEN
to_parse = f"name @ {url}"
# WHEN
req = Requirement(to_parse)
# THEN
assert req.url == url
def test_empty_extras(self) -> None:
# GIVEN
to_parse = "name[]"
# WHEN
req = Requirement(to_parse)
# THEN
assert req.name == "name"
assert req.extras == set()
def test_empty_specifier(self) -> None:
# GIVEN
to_parse = "name()"
# WHEN
req = Requirement(to_parse)
# THEN
assert req.name == "name"
assert req.specifier == ""
# ----------------------------------------------------------------------------------
# Everything below this (in this class) should be parsing failure modes
# ----------------------------------------------------------------------------------
# Start all method names with with `test_error_`
# to make it easier to run these tests with `-k error`
def test_error_when_empty_string(self) -> None:
# GIVEN
to_parse = ""
# WHEN
with pytest.raises(InvalidRequirement) as ctx:
Requirement(to_parse)
# THEN
assert ctx.exconly() == (
"packaging.requirements.InvalidRequirement: "
"Expected package name at the start of dependency specifier\n"
" \n"
" ^"
)
def test_error_no_name(self) -> None:
# GIVEN
to_parse = "==0.0"
# WHEN
with pytest.raises(InvalidRequirement) as ctx:
Requirement(to_parse)
# THEN
assert ctx.exconly() == (
"packaging.requirements.InvalidRequirement: "
"Expected package name at the start of dependency specifier\n"
" ==0.0\n"
" ^"
)
def test_error_when_missing_comma_in_extras(self) -> None:
# GIVEN
to_parse = "name[bar baz]"
# WHEN
with pytest.raises(InvalidRequirement) as ctx:
Requirement(to_parse)
# THEN
assert ctx.exconly() == (
"packaging.requirements.InvalidRequirement: "
"Expected comma between extra names\n"
" name[bar baz]\n"
" ^"
)
def test_error_when_trailing_comma_in_extras(self) -> None:
# GIVEN
to_parse = "name[bar, baz,]"
# WHEN
with pytest.raises(InvalidRequirement) as ctx:
Requirement(to_parse)
# THEN
assert ctx.exconly() == (
"packaging.requirements.InvalidRequirement: "
"Expected extra name after comma\n"
" name[bar, baz,]\n"
" ^"
)
def test_error_when_parens_not_closed_correctly(self) -> None:
# GIVEN
to_parse = "name (>= 1.0"
# WHEN
with pytest.raises(InvalidRequirement) as ctx:
Requirement(to_parse)
# THEN
assert ctx.exconly() == (
"packaging.requirements.InvalidRequirement: "
"Expected matching RIGHT_PARENTHESIS for LEFT_PARENTHESIS, "
"after version specifier\n"
" name (>= 1.0\n"
" ~~~~~~~^"
)
def test_error_when_prefix_match_is_used_incorrectly(self) -> None:
# GIVEN
to_parse = "black (>=20.*) ; extra == 'format'"
# WHEN
with pytest.raises(InvalidRequirement) as ctx:
Requirement(to_parse)
# THEN
assert ctx.exconly() == (
"packaging.requirements.InvalidRequirement: "
".* suffix can only be used with `==` or `!=` operators\n"
" black (>=20.*) ; extra == 'format'\n"
" ~~~~~^"
)
@pytest.mark.parametrize("operator", [">=", "<=", ">", "<", "~="])
def test_error_when_local_version_label_is_used_incorrectly(
self, operator: str
) -> None:
# GIVEN
to_parse = f"name {operator} 1.0+local.version.label"
op_tilde = len(operator) * "~"
# WHEN
with pytest.raises(InvalidRequirement) as ctx:
Requirement(to_parse)
# THEN
assert ctx.exconly() == (
"packaging.requirements.InvalidRequirement: "
"Local version label can only be used with `==` or `!=` operators\n"
f" name {operator} 1.0+local.version.label\n"
f" {op_tilde}~~~~^"
)
def test_error_when_bracket_not_closed_correctly(self) -> None:
# GIVEN
to_parse = "name[bar, baz >= 1.0"
# WHEN
with pytest.raises(InvalidRequirement) as ctx:
Requirement(to_parse)
# THEN
assert ctx.exconly() == (
"packaging.requirements.InvalidRequirement: "
"Expected matching RIGHT_BRACKET for LEFT_BRACKET, "
"after extras\n"
" name[bar, baz >= 1.0\n"
" ~~~~~~~~~~^"
)
def test_error_when_extras_bracket_left_unclosed(self) -> None:
# GIVEN
to_parse = "name[bar, baz"
# WHEN
with pytest.raises(InvalidRequirement) as ctx:
Requirement(to_parse)
# THEN
assert ctx.exconly() == (
"packaging.requirements.InvalidRequirement: "
"Expected matching RIGHT_BRACKET for LEFT_BRACKET, "
"after extras\n"
" name[bar, baz\n"
" ~~~~~~~~~^"
)
def test_error_no_space_after_url(self) -> None:
# GIVEN
to_parse = "name @ https://example.com/; extra == 'example'"
# WHEN
with pytest.raises(InvalidRequirement) as ctx:
Requirement(to_parse)
# THEN
assert ctx.exconly() == (
"packaging.requirements.InvalidRequirement: "
"Expected semicolon (after URL and whitespace) or end\n"
" name @ https://example.com/; extra == 'example'\n"
" ~~~~~~~~~~~~~~~~~~~~~~^"
)
def test_error_marker_bracket_unclosed(self) -> None:
# GIVEN
to_parse = "name; (extra == 'example'"
# WHEN
with pytest.raises(InvalidRequirement) as ctx:
Requirement(to_parse)
# THEN
assert ctx.exconly() == (
"packaging.requirements.InvalidRequirement: "
"Expected matching RIGHT_PARENTHESIS for LEFT_PARENTHESIS, "
"after marker expression\n"
" name; (extra == 'example'\n"
" ~~~~~~~~~~~~~~~~~~~^"
)
def test_error_no_url_after_at(self) -> None:
# GIVEN
to_parse = "name @ "
# WHEN
with pytest.raises(InvalidRequirement) as ctx:
Requirement(to_parse)
# THEN
assert ctx.exconly() == (
"packaging.requirements.InvalidRequirement: "
"Expected URL after @\n"
" name @ \n"
" ^"
)
def test_error_invalid_marker_lvalue(self) -> None:
# GIVEN
to_parse = "name; invalid_name"
# WHEN
with pytest.raises(InvalidRequirement) as ctx:
Requirement(to_parse)
# THEN
assert ctx.exconly() == (
"packaging.requirements.InvalidRequirement: "
"Expected a marker variable or quoted string\n"
" name; invalid_name\n"
" ^"
)
def test_error_invalid_marker_rvalue(self) -> None:
# GIVEN
to_parse = "name; '3.7' <= invalid_name"
# WHEN
with pytest.raises(InvalidRequirement) as ctx:
Requirement(to_parse)
# THEN
assert ctx.exconly() == (
"packaging.requirements.InvalidRequirement: "
"Expected a marker variable or quoted string\n"
" name; '3.7' <= invalid_name\n"
" ^"
)
def test_error_invalid_marker_notin_without_whitespace(self) -> None:
# GIVEN
to_parse = "name; '3.7' notin python_version"
# WHEN
with pytest.raises(InvalidRequirement) as ctx:
Requirement(to_parse)
# THEN
assert ctx.exconly() == (
"packaging.requirements.InvalidRequirement: "
"Expected marker operator, one of <=, <, !=, ==, >=, >, ~=, ===, "
"in, not in\n"
" name; '3.7' notin python_version\n"
" ^"
)
def test_error_when_no_word_boundary(self) -> None:
# GIVEN
to_parse = "name; '3.6'inpython_version"
# WHEN
with pytest.raises(InvalidRequirement) as ctx:
Requirement(to_parse)
# THEN
assert ctx.exconly() == (
"packaging.requirements.InvalidRequirement: "
"Expected marker operator, one of <=, <, !=, ==, >=, >, ~=, ===, "
"in, not in\n"
" name; '3.6'inpython_version\n"
" ^"
)
def test_error_invalid_marker_not_without_in(self) -> None:
# GIVEN
to_parse = "name; '3.7' not python_version"
# WHEN
with pytest.raises(InvalidRequirement) as ctx:
Requirement(to_parse)
# THEN
assert ctx.exconly() == (
"packaging.requirements.InvalidRequirement: "
"Expected 'in' after 'not'\n"
" name; '3.7' not python_version\n"
" ^"
)
def test_error_invalid_marker_with_invalid_op(self) -> None:
# GIVEN
to_parse = "name; '3.7' ~ python_version"
# WHEN
with pytest.raises(InvalidRequirement) as ctx:
Requirement(to_parse)
# THEN
assert ctx.exconly() == (
"packaging.requirements.InvalidRequirement: "
"Expected marker operator, one of <=, <, !=, ==, >=, >, ~=, ===, "
"in, not in\n"
" name; '3.7' ~ python_version\n"
" ^"
)
def test_error_on_legacy_version_outside_triple_equals(self) -> None:
# GIVEN
to_parse = "name==1.0.org1"
# WHEN
with pytest.raises(InvalidRequirement) as ctx:
Requirement(to_parse)
# THEN
assert ctx.exconly() == (
"packaging.requirements.InvalidRequirement: "
"Expected comma (within version specifier), "
"semicolon (after version specifier) or end\n"
" name==1.0.org1\n"
" ~~~~~^"
)
def test_error_on_missing_version_after_op(self) -> None:
# GIVEN
to_parse = "name=="
# WHEN
with pytest.raises(InvalidRequirement) as ctx:
Requirement(to_parse)
# THEN
assert ctx.exconly() == (
"packaging.requirements.InvalidRequirement: "
"Expected semicolon (after name with no version specifier) or end\n"
" name==\n"
" ^"
)
def test_error_on_missing_op_after_name(self) -> None:
# GIVEN
to_parse = "name 1.0"
# WHEN
with pytest.raises(InvalidRequirement) as ctx:
Requirement(to_parse)
# THEN
assert ctx.exconly() == (
"packaging.requirements.InvalidRequirement: "
"Expected semicolon (after name with no version specifier) or end\n"
" name 1.0\n"
" ^"
)
def test_error_on_random_char_after_specifier(self) -> None:
# GIVEN
to_parse = "name >= 1.0 #"
# WHEN
with pytest.raises(InvalidRequirement) as ctx:
Requirement(to_parse)
# THEN
assert ctx.exconly() == (
"packaging.requirements.InvalidRequirement: "
"Expected comma (within version specifier), "
"semicolon (after version specifier) or end\n"
" name >= 1.0 #\n"
" ~~~~~~~^"
)
def test_error_on_missing_comma_in_specifier(self) -> None:
# GIVEN
to_parse = "name >= 1.0 <= 2.0"
# WHEN
with pytest.raises(InvalidRequirement) as ctx:
Requirement(to_parse)
# THEN
assert ctx.exconly() == (
"packaging.requirements.InvalidRequirement: "
"Expected comma (within version specifier), "
"semicolon (after version specifier) or end\n"
" name >= 1.0 <= 2.0\n"
" ~~~~~~~^"
)
class TestRequirementBehaviour:
def test_types_with_nothing(self) -> None:
# GIVEN
to_parse = "foobar"
# WHEN
req = Requirement(to_parse)
# THEN
assert isinstance(req.name, str)
assert isinstance(req.extras, set)
assert req.url is None
assert isinstance(req.specifier, SpecifierSet)
assert req.marker is None
def test_types_with_specifier_and_marker(self) -> None:
# GIVEN
to_parse = "foobar[quux]<2,>=3; os_name=='a'"
# WHEN
req = Requirement(to_parse)
# THEN
assert isinstance(req.name, str)
assert isinstance(req.extras, set)
assert req.url is None
assert isinstance(req.specifier, SpecifierSet)
assert isinstance(req.marker, Marker)
def test_types_with_url(self) -> None:
req = Requirement("foobar @ http://foo.com")
assert isinstance(req.name, str)
assert isinstance(req.extras, set)
assert isinstance(req.url, str)
assert isinstance(req.specifier, SpecifierSet)
assert req.marker is None
@pytest.mark.parametrize(
"url_or_specifier",
["", " @ https://url ", "!=2.0", "==2.*"],
)
@pytest.mark.parametrize("extras", ["", "[a]", "[a,b]", "[a1,b1,b2]"])
@pytest.mark.parametrize(
"marker",
["", '; python_version == "3.11"', '; "3." not in python_version'],
)
def test_str_and_repr(
self, extras: str, url_or_specifier: str, marker: str
) -> None:
# GIVEN
to_parse = f"name{extras}{url_or_specifier}{marker}"
# WHEN
req = Requirement(to_parse)
# THEN
assert str(req) == to_parse.strip()
assert repr(req) == f""
@pytest.mark.parametrize(("dep1", "dep2"), EQUAL_DEPENDENCIES)
def test_equal_reqs_equal_hashes(self, dep1: str, dep2: str) -> None:
"""Requirement objects created from equal strings should be equal."""
# GIVEN / WHEN
req1, req2 = Requirement(dep1), Requirement(dep2)
assert req1 == req2
assert hash(req1) == hash(req2)
@pytest.mark.parametrize(("dep1", "dep2"), EQUIVALENT_DEPENDENCIES)
def test_equivalent_reqs_equal_hashes_unequal_strings(
self, dep1: str, dep2: str
) -> None:
"""Requirement objects created from equivalent strings should be equal,
even though their string representation will not."""
# GIVEN / WHEN
req1, req2 = Requirement(dep1), Requirement(dep2)
assert req1 == req2
assert hash(req1) == hash(req2)
assert str(req1) != str(req2)
@pytest.mark.parametrize(("dep1", "dep2"), DIFFERENT_DEPENDENCIES)
def test_different_reqs_different_hashes(self, dep1: str, dep2: str) -> None:
"""Requirement objects created from non-equivalent strings should differ."""
# GIVEN / WHEN
req1, req2 = Requirement(dep1), Requirement(dep2)
# THEN
assert req1 != req2
assert hash(req1) != hash(req2)
def test_compare_with_string(self) -> None:
assert Requirement("packaging>=21.3") != "packaging>=21.3"
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1768936045.8193686
packaging-26.0/tests/test_specifiers.py 0000644 0000000 0000000 00000227116 15133751156 015242 0 ustar 00 # This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import annotations
import itertools
import operator
import re
import typing
import pytest
from packaging.specifiers import InvalidSpecifier, Specifier, SpecifierSet
from packaging.version import Version, parse
from .test_version import VERSIONS
if typing.TYPE_CHECKING:
from collections.abc import Callable
LEGACY_SPECIFIERS = [
"==2.1.0.3",
"!=2.2.0.5",
"<=5",
">=7.9a1",
"<1.0.dev1",
">2.0.post1",
]
SPECIFIERS = [
"~=2.0",
"==2.1.*",
"==2.1.0.3",
"!=2.2.*",
"!=2.2.0.5",
"<=5",
">=7.9a1",
"<1.0.dev1",
">2.0.post1",
]
class TestSpecifier:
@pytest.mark.parametrize("specifier", SPECIFIERS)
def test_specifiers_valid(self, specifier: str) -> None:
Specifier(specifier)
def test_match_args(self) -> None:
assert Specifier.__match_args__ == ("_str",)
assert Specifier(">=1.0")._str == ">=1.0"
@pytest.mark.parametrize(
"specifier",
[
# Operator-less specifier
"2.0",
# Invalid operator
"=>2.0",
# Version-less specifier
"==",
# Local segment on operators which don't support them
"~=1.0+5",
">=1.0+deadbeef",
"<=1.0+abc123",
">1.0+watwat",
"<1.0+1.0",
# Prefix matching on operators which don't support them
"~=1.0.*",
">=1.0.*",
"<=1.0.*",
">1.0.*",
"<1.0.*",
# Combination of local and prefix matching on operators which do
# support one or the other
"==1.0.*+5",
"!=1.0.*+deadbeef",
# Prefix matching cannot be used with a pre-release, post-release,
# dev or local version
"==2.0a1.*",
"!=2.0a1.*",
"==2.0.post1.*",
"!=2.0.post1.*",
"==2.0.dev1.*",
"!=2.0.dev1.*",
"==1.0+5.*",
"!=1.0+deadbeef.*",
# Prefix matching must appear at the end
"==1.0.*.5",
# Compatible operator requires 2 digits in the release operator
"~=1",
# Cannot use a prefix matching after a .devN version
"==1.0.dev1.*",
"!=1.0.dev1.*",
],
)
def test_specifiers_invalid(self, specifier: str) -> None:
with pytest.raises(InvalidSpecifier):
Specifier(specifier)
@pytest.mark.parametrize(
"version",
[
# Various development release incarnations
"1.0dev",
"1.0.dev",
"1.0dev1",
"1.0-dev",
"1.0-dev1",
"1.0DEV",
"1.0.DEV",
"1.0DEV1",
"1.0.DEV1",
"1.0-DEV",
"1.0-DEV1",
# Various alpha incarnations
"1.0a",
"1.0.a",
"1.0.a1",
"1.0-a",
"1.0-a1",
"1.0alpha",
"1.0.alpha",
"1.0.alpha1",
"1.0-alpha",
"1.0-alpha1",
"1.0A",
"1.0.A",
"1.0.A1",
"1.0-A",
"1.0-A1",
"1.0ALPHA",
"1.0.ALPHA",
"1.0.ALPHA1",
"1.0-ALPHA",
"1.0-ALPHA1",
# Various beta incarnations
"1.0b",
"1.0.b",
"1.0.b1",
"1.0-b",
"1.0-b1",
"1.0beta",
"1.0.beta",
"1.0.beta1",
"1.0-beta",
"1.0-beta1",
"1.0B",
"1.0.B",
"1.0.B1",
"1.0-B",
"1.0-B1",
"1.0BETA",
"1.0.BETA",
"1.0.BETA1",
"1.0-BETA",
"1.0-BETA1",
# Various release candidate incarnations
"1.0c",
"1.0.c",
"1.0.c1",
"1.0-c",
"1.0-c1",
"1.0rc",
"1.0.rc",
"1.0.rc1",
"1.0-rc",
"1.0-rc1",
"1.0C",
"1.0.C",
"1.0.C1",
"1.0-C",
"1.0-C1",
"1.0RC",
"1.0.RC",
"1.0.RC1",
"1.0-RC",
"1.0-RC1",
# Various post release incarnations
"1.0post",
"1.0.post",
"1.0post1",
"1.0-post",
"1.0-post1",
"1.0POST",
"1.0.POST",
"1.0POST1",
"1.0.POST1",
"1.0-POST",
"1.0-POST1",
"1.0-5",
# Local version case insensitivity
"1.0+AbC",
# Integer Normalization
"1.01",
"1.0a05",
"1.0b07",
"1.0c056",
"1.0rc09",
"1.0.post000",
"1.1.dev09000",
"00!1.2",
"0100!0.0",
# Various other normalizations
"v1.0",
" \r \f \v v1.0\t\n",
],
)
def test_specifiers_normalized(self, version: str) -> None:
if "+" not in version:
ops = ["~=", "==", "!=", "<=", ">=", "<", ">"]
else:
ops = ["==", "!="]
for op in ops:
Specifier(op + version)
@pytest.mark.parametrize(
("specifier", "expected"),
[
# Single item specifiers should just be reflexive
("!=2.0", "!=2.0"),
("<2.0", "<2.0"),
("<=2.0", "<=2.0"),
("==2.0", "==2.0"),
(">2.0", ">2.0"),
(">=2.0", ">=2.0"),
("~=2.0", "~=2.0"),
# Spaces should be removed
("< 2", "<2"),
],
)
def test_specifiers_str_and_repr(self, specifier: str, expected: str) -> None:
spec = Specifier(specifier)
assert str(spec) == expected
assert repr(spec) == f""
@pytest.mark.parametrize("specifier", SPECIFIERS)
def test_specifiers_hash(self, specifier: str) -> None:
assert hash(Specifier(specifier)) == hash(Specifier(specifier))
@pytest.mark.parametrize(
("left", "right", "op"),
itertools.chain.from_iterable(
# Verify that the equal (==) operator works correctly
[[(x, x, operator.eq) for x in SPECIFIERS]]
+
# Verify that the not equal (!=) operator works correctly
[
[(x, y, operator.ne) for j, y in enumerate(SPECIFIERS) if i != j]
for i, x in enumerate(SPECIFIERS)
]
),
)
def test_comparison_true(
self,
left: str,
right: str,
op: typing.Callable[[Specifier | str, Specifier | str], bool],
) -> None:
assert op(Specifier(left), Specifier(right))
assert op(left, Specifier(right))
assert op(Specifier(left), right)
@pytest.mark.parametrize(("left", "right"), [("==2.8.0", "==2.8")])
def test_comparison_canonicalizes(self, left: str, right: str) -> None:
assert Specifier(left) == Specifier(right)
assert left == Specifier(right)
assert Specifier(left) == right
@pytest.mark.parametrize(
("left", "right", "op"),
itertools.chain.from_iterable(
# Verify that the equal (==) operator works correctly
[[(x, x, operator.ne) for x in SPECIFIERS]]
+
# Verify that the not equal (!=) operator works correctly
[
[(x, y, operator.eq) for j, y in enumerate(SPECIFIERS) if i != j]
for i, x in enumerate(SPECIFIERS)
]
),
)
def test_comparison_false(
self,
left: str,
right: str,
op: typing.Callable[[Specifier | str, Specifier | str], bool],
) -> None:
assert not op(Specifier(left), Specifier(right))
assert not op(left, Specifier(right))
assert not op(Specifier(left), right)
def test_comparison_non_specifier(self) -> None:
assert Specifier("==1.0") != 12
assert not Specifier("==1.0") == 12
assert Specifier("==1.0") != "12"
assert not Specifier("==1.0") == "12"
@pytest.mark.parametrize(
("version", "spec_str", "expected"),
[
(v, s, True)
for v, s in [
# Test the equality operation
("2.0", "==2"),
("2.0", "==2.0"),
("2.0", "==2.0.0"),
("2.0+deadbeef", "==2"),
("2.0+deadbeef", "==2.0"),
("2.0+deadbeef", "==2.0.0"),
("2.0+deadbeef", "==2+deadbeef"),
("2.0+deadbeef", "==2.0+deadbeef"),
("2.0+deadbeef", "==2.0.0+deadbeef"),
("2.0+deadbeef.0", "==2.0.0+deadbeef.00"),
# Test the equality operation with a prefix
("2.dev1", "==2.*"),
("2a1", "==2.*"),
("2a1.post1", "==2.*"),
("2b1", "==2.*"),
("2b1.dev1", "==2.*"),
("2c1", "==2.*"),
("2c1.post1.dev1", "==2.*"),
("2c1.post1.dev1", "==2.0.*"),
("2rc1", "==2.*"),
("2rc1", "==2.0.*"),
("2", "==2.*"),
("2", "==2.0.*"),
("2", "==0!2.*"),
("0!2", "==2.*"),
("2.0", "==2.*"),
("2.0.0", "==2.*"),
("2.1+local.version", "==2.1.*"),
# Test the in-equality operation
("2.1", "!=2"),
("2.1", "!=2.0"),
("2.0.1", "!=2"),
("2.0.1", "!=2.0"),
("2.0.1", "!=2.0.0"),
("2.0", "!=2.0+deadbeef"),
# Test the in-equality operation with a prefix
("2.0", "!=3.*"),
("2.1", "!=2.0.*"),
# Test the greater than equal operation
("2.0", ">=2"),
("2.0", ">=2.0"),
("2.0", ">=2.0.0"),
("2.0.post1", ">=2"),
("2.0.post1.dev1", ">=2"),
("3", ">=2"),
("3.0.0a8", ">=3.0.0a7"),
# Test the less than equal operation
("2.0", "<=2"),
("2.0", "<=2.0"),
("2.0", "<=2.0.0"),
("2.0.dev1", "<=2"),
("2.0a1", "<=2"),
("2.0a1.dev1", "<=2"),
("2.0b1", "<=2"),
("2.0b1.post1", "<=2"),
("2.0c1", "<=2"),
("2.0c1.post1.dev1", "<=2"),
("2.0rc1", "<=2"),
("1", "<=2"),
("3.0.0a7", "<=3.0.0a8"),
# Test the greater than operation
("3", ">2"),
("2.1", ">2.0"),
("2.0.1", ">2"),
("2.1.post1", ">2"),
("2.1+local.version", ">2"),
("3.0.0a8", ">3.0.0a7"),
# Test the less than operation
("1", "<2"),
("2.0", "<2.1"),
("2.0.dev0", "<2.1"),
("3.0.0a7", "<3.0.0a8"),
# Test the compatibility operation
("1", "~=1.0"),
("1.0.1", "~=1.0"),
("1.1", "~=1.0"),
("1.9999999", "~=1.0"),
("1.1", "~=1.0a1"),
("2022.01.01", "~=2022.01.01"),
# Test that epochs are handled sanely
("2!1.0", "~=2!1.0"),
("2!1.0", "==2!1.*"),
("2!1.0", "==2!1.0"),
("2!1.0", "!=1.0"),
("2!1.0.0", "==2!1.0.0.0.*"),
("2!1.0.0", "==2!1.0.*"),
("2!1.0.0", "==2!1.*"),
("1.0", "!=2!1.0"),
("1.0", "<=2!0.1"),
("2!1.0", ">=2.0"),
("1.0", "<2!0.1"),
("2!1.0", ">2.0"),
# Test some normalization rules
("2.0.5", ">2.0dev"),
]
]
+ [
(v, s, False)
for v, s in [
# Test the equality operation
("2.1", "==2"),
("2.1", "==2.0"),
("2.1", "==2.0.0"),
("2.0", "==2.0+deadbeef"),
# Test the equality operation with a prefix
("2.0", "==3.*"),
("2.1", "==2.0.*"),
# Test the in-equality operation
("2.0", "!=2"),
("2.0", "!=2.0"),
("2.0", "!=2.0.0"),
("2.0+deadbeef", "!=2"),
("2.0+deadbeef", "!=2.0"),
("2.0+deadbeef", "!=2.0.0"),
("2.0+deadbeef", "!=2+deadbeef"),
("2.0+deadbeef", "!=2.0+deadbeef"),
("2.0+deadbeef", "!=2.0.0+deadbeef"),
("2.0+deadbeef.0", "!=2.0.0+deadbeef.00"),
# Test the in-equality operation with a prefix
("2.dev1", "!=2.*"),
("2a1", "!=2.*"),
("2a1.post1", "!=2.*"),
("2b1", "!=2.*"),
("2b1.dev1", "!=2.*"),
("2c1", "!=2.*"),
("2c1.post1.dev1", "!=2.*"),
("2c1.post1.dev1", "!=2.0.*"),
("2rc1", "!=2.*"),
("2rc1", "!=2.0.*"),
("2", "!=2.*"),
("2", "!=2.0.*"),
("2.0", "!=2.*"),
("2.0.0", "!=2.*"),
# Test the greater than equal operation
("2.0.dev1", ">=2"),
("2.0a1", ">=2"),
("2.0a1.dev1", ">=2"),
("2.0b1", ">=2"),
("2.0b1.post1", ">=2"),
("2.0c1", ">=2"),
("2.0c1.post1.dev1", ">=2"),
("2.0rc1", ">=2"),
("1", ">=2"),
# Test the less than equal operation
("2.0.post1", "<=2"),
("2.0.post1.dev1", "<=2"),
("3", "<=2"),
# Test the greater than operation
("1", ">2"),
("2.0.dev1", ">2"),
("2.0a1", ">2"),
("2.0a1.post1", ">2"),
("2.0b1", ">2"),
("2.0b1.dev1", ">2"),
("2.0c1", ">2"),
("2.0c1.post1.dev1", ">2"),
("2.0rc1", ">2"),
("2.0", ">2"),
("2.0.post1", ">2"),
("2.0.post1.dev1", ">2"),
("2.0+local.version", ">2"),
("1.0+local", ">1.0.dev1"),
# Test the less than operation
("2.0.dev1", "<2"),
("2.0a1", "<2"),
("2.0a1.post1", "<2"),
("2.0b1", "<2"),
("2.0b2.dev1", "<2"),
("2.0c1", "<2"),
("2.0c1.post1.dev1", "<2"),
("2.0rc1", "<2"),
("2.0", "<2"),
("2.post1", "<2"),
("2.post1.dev1", "<2"),
("3", "<2"),
# Test the compatibility operation
("2.0", "~=1.0"),
("1.1.0", "~=1.0.0"),
("1.1.post1", "~=1.0.0"),
# Test that epochs are handled sanely
("1.0", "~=2!1.0"),
("2!1.0", "~=1.0"),
("2!1.0", "==1.0"),
("1.0", "==2!1.0"),
("2!1.0", "==1.0.0.*"),
("1.0", "==2!1.0.0.*"),
("2!1.0", "==1.*"),
("1.0", "==2!1.*"),
("2!1.0", "!=2!1.0"),
]
],
)
def test_specifiers(self, version: str, spec_str: str, expected: bool) -> None:
spec = Specifier(spec_str, prereleases=True)
if expected:
# Test that the plain string form works
assert version in spec
assert spec.contains(version)
# Test that the version instance form works
assert Version(version) in spec
assert spec.contains(Version(version))
else:
# Test that the plain string form works
assert version not in spec
assert not spec.contains(version)
# Test that the version instance form works
assert Version(version) not in spec
assert not spec.contains(Version(version))
@pytest.mark.parametrize(
("spec_str", "version", "expected"),
[
("==1.0", "not a valid version", False),
("==1.*", "not a valid version", False),
(">=1.0", "not a valid version", False),
(">1.0", "not a valid version", False),
("<=1.0", "not a valid version", False),
("<1.0", "not a valid version", False),
("~=1.0", "not a valid version", False),
("!=1.0", "not a valid version", False),
("!=1.*", "not a valid version", False),
# Test with arbitrary equality (===)
("===invalid", "invalid", True),
("===foobar", "invalid", False),
],
)
def test_invalid_version(self, spec_str: str, version: str, expected: bool) -> None:
spec = Specifier(spec_str, prereleases=True)
assert spec.contains(version) == expected
@pytest.mark.parametrize(
(
"specifier",
"initial_prereleases",
"set_prereleases",
"version",
"initial_contains",
"final_contains",
),
[
(">1.0", None, True, "1.0.dev1", False, False),
# Setting prereleases to True explicitly includes prerelease versions
(">1.0", None, True, "2.0.dev1", True, True),
(">1.0", False, True, "2.0.dev1", False, True),
# Setting prereleases to False explicitly excludes prerelease versions
(">1.0", None, False, "2.0.dev1", True, False),
# Setting prereleases to None falls back to default behavior
(">1.0", True, None, "2.0.dev1", True, True),
(">1.0", False, None, "2.0.dev1", False, True),
# Different specifiers with prerelease versions
(">=2.0.dev1", None, True, "2.0a1", True, True),
(">=2.0.dev1", None, False, "2.0a1", True, False),
# Alpha/beta/rc/dev variations
(">1.0", None, True, "2.0a1", True, True),
(">1.0", None, True, "2.0b1", True, True),
(">1.0", None, True, "2.0rc1", True, True),
# Edge cases
("==2.0.*", None, True, "2.0.dev1", True, True),
("==2.0.*", None, False, "2.0.dev1", True, False),
# Specifiers that already include prereleases implicitly
("<1.0.dev1", None, False, "0.9.dev1", True, False),
(">1.0.dev1", None, None, "1.1.dev1", True, True),
# Multiple changes to the prereleases setting
(">1.0", True, False, "2.0.dev1", True, False),
],
)
def test_specifier_prereleases_set(
self,
specifier: str,
initial_prereleases: bool | None,
set_prereleases: bool | None,
version: str,
initial_contains: bool,
final_contains: bool,
) -> None:
"""Test setting prereleases property."""
spec = Specifier(specifier, prereleases=initial_prereleases)
assert (version in spec) == initial_contains
assert spec.contains(version) == initial_contains
spec.prereleases = set_prereleases
assert (version in spec) == final_contains
assert spec.contains(version) == final_contains
@pytest.mark.parametrize(
("version", "spec_str", "expected"),
[
("1.0.0", "===1.0", False),
("1.0.dev0", "===1.0", False),
# Test identity comparison by itself
("1.0", "===1.0", True),
("1.0.dev0", "===1.0.dev0", True),
# Test that local versions don't match
("1.0+downstream1", "===1.0", False),
("1.0", "===1.0+downstream1", False),
# Test with arbitrary (non-version) strings
("foobar", "===foobar", True),
("foobar", "===baz", False),
# Test case insensitivity for pre-release versions
("1.0a1", "===1.0a1", True),
("1.0A1", "===1.0A1", True),
("1.0a1", "===1.0A1", True),
("1.0A1", "===1.0a1", True),
# Test case insensitivity for beta versions
("1.0b1", "===1.0b1", True),
("1.0B1", "===1.0B1", True),
("1.0b1", "===1.0B1", True),
("1.0B1", "===1.0b1", True),
# Test case insensitivity for release candidate versions
("1.0rc1", "===1.0rc1", True),
("1.0RC1", "===1.0RC1", True),
("1.0rc1", "===1.0RC1", True),
("1.0RC1", "===1.0rc1", True),
# Test case insensitivity for post-release versions
("1.0.post1", "===1.0.post1", True),
("1.0.POST1", "===1.0.POST1", True),
("1.0.post1", "===1.0.POST1", True),
("1.0.POST1", "===1.0.post1", True),
# Test case insensitivity for dev versions
("1.0.dev1", "===1.0.dev1", True),
("1.0.DEV1", "===1.0.DEV1", True),
("1.0.dev1", "===1.0.DEV1", True),
("1.0.DEV1", "===1.0.dev1", True),
# Test case insensitivity with local versions
("1.0+local", "===1.0+local", True),
("1.0+LOCAL", "===1.0+LOCAL", True),
("1.0+local", "===1.0+LOCAL", True),
("1.0+LOCAL", "===1.0+local", True),
("1.0+abc.def", "===1.0+abc.def", True),
("1.0+ABC.DEF", "===1.0+ABC.DEF", True),
("1.0+abc.def", "===1.0+ABC.DEF", True),
("1.0+ABC.DEF", "===1.0+abc.def", True),
# Test case insensitivity with mixed case letters in local
("1.0+AbC", "===1.0+AbC", True),
("1.0+AbC", "===1.0+abc", True),
("1.0+AbC", "===1.0+ABC", True),
# Test complex cases with multiple segments
("1.0a1.post2.dev3", "===1.0a1.post2.dev3", True),
("1.0A1.POST2.DEV3", "===1.0A1.POST2.DEV3", True),
("1.0a1.post2.dev3", "===1.0A1.POST2.DEV3", True),
("1.0A1.POST2.DEV3", "===1.0a1.post2.dev3", True),
# Test case insensitivity of non-PEP 440 versions
("lolwat", "===LOLWAT", True),
("lolwat", "===LoLWaT", True),
("LOLWAT", "===lolwat", True),
("LoLWaT", "===lOlwAt", True),
],
)
def test_arbitrary_equality(
self, version: str, spec_str: str, expected: bool
) -> None:
spec = Specifier(spec_str)
assert spec.contains(version) == expected
@pytest.mark.parametrize(
("specifier", "expected"),
[
("==1.0", False),
(">=1.0", False),
("<=1.0", False),
("~=1.0", False),
("<1.0", False),
(">1.0", False),
("<1.0.dev1", True),
(">1.0.dev1", True),
("!=1.0.dev1", False),
("==1.0.*", False),
("==1.0.dev1", True),
(">=1.0.dev1", True),
("<=1.0.dev1", True),
("~=1.0.dev1", True),
],
)
def test_specifier_prereleases_detection(
self, specifier: str, expected: bool
) -> None:
assert Specifier(specifier).prereleases == expected
@pytest.mark.parametrize(
("specifier", "version", "spec_pre", "contains_pre", "expected"),
[
(">=1.0", "2.0.dev1", None, None, True),
(">=2.0.dev1", "2.0a1", None, None, True),
("==2.0.*", "2.0a1.dev1", None, None, True),
("<=2.0", "1.0.dev1", None, None, True),
("<=2.0.dev1", "1.0a1", None, None, True),
("<2.0", "2.0a1", None, None, False),
("<2.0a2", "2.0a1", None, None, True),
("<=2.0", "1.0.dev1", False, None, False),
("<=2.0a1", "1.0.dev1", False, None, False),
("<=2.0", "1.0.dev1", None, False, False),
("<=2.0a1", "1.0.dev1", None, False, False),
("<=2.0", "1.0.dev1", True, False, False),
("<=2.0a1", "1.0.dev1", True, False, False),
("<=2.0", "1.0.dev1", False, True, True),
("<=2.0a1", "1.0.dev1", False, True, True),
],
)
def test_specifiers_prereleases(
self,
specifier: str,
version: str,
spec_pre: bool | None,
contains_pre: bool | None,
expected: bool,
) -> None:
spec = Specifier(specifier, prereleases=spec_pre)
assert spec.contains(version, prereleases=contains_pre) == expected
@pytest.mark.parametrize(
("specifier", "specifier_prereleases", "prereleases", "input", "expected"),
[
# General test of the filter method
(">=1.0.dev1", None, None, ["1.0", "2.0a1"], ["1.0", "2.0a1"]),
(">=1.2.3", None, None, ["1.2", "1.5a1"], ["1.5a1"]),
(">=1.2.3", None, None, ["1.3", "1.5a1"], ["1.3"]),
(">=1.0", None, None, ["2.0a1"], ["2.0a1"]),
("!=2.0a1", None, None, ["1.0a2", "1.0", "2.0a1"], ["1.0"]),
("==2.0a1", None, None, ["2.0a1"], ["2.0a1"]),
(">2.0a1", None, None, ["2.0a1", "3.0a2", "3.0"], ["3.0a2", "3.0"]),
("<2.0a1", None, None, ["1.0a2", "1.0", "2.0a1"], ["1.0a2", "1.0"]),
("~=2.0a1", None, None, ["1.0", "2.0a1", "3.0a2", "3.0"], ["2.0a1"]),
# Test overriding with the prereleases parameter on filter
(">=1.0.dev1", None, False, ["1.0", "2.0a1"], ["1.0"]),
# Test overriding with the overall specifier
(">=1.0.dev1", True, None, ["1.0", "2.0a1"], ["1.0", "2.0a1"]),
(">=1.0.dev1", False, None, ["1.0", "2.0a1"], ["1.0"]),
# Test when both specifier and filter have prerelease value
(">=1.0", True, False, ["1.0", "2.0a1"], ["1.0"]),
(">=1.0", False, True, ["1.0", "2.0a1"], ["1.0", "2.0a1"]),
(">=1.0", True, True, ["1.0", "2.0a1"], ["1.0", "2.0a1"]),
(">=1.0", False, False, ["1.0", "2.0a1"], ["1.0"]),
# Test that invalid versions are discarded
(">=1.0", None, None, ["not a valid version"], []),
(">=1.0", None, None, ["1.0", "not a valid version"], ["1.0"]),
# Test arbitrary equality (===)
("===foobar", None, None, ["foobar", "foo", "bar"], ["foobar"]),
("===foobar", None, None, ["foo", "bar"], []),
# Test that === does not match with zero padding
("===1.0", None, None, ["1.0", "1.0.0", "2.0"], ["1.0"]),
# Test that === does not match with local versions
("===1.0", None, None, ["1.0", "1.0+downstream1"], ["1.0"]),
# Test === with mix of valid versions and arbitrary strings
(
"===foobar",
None,
None,
["foobar", "1.0", "2.0a1", "invalid"],
["foobar"],
),
("===1.0", None, None, ["1.0", "foobar", "invalid", "1.0.0"], ["1.0"]),
# Test != with invalid versions (should not pass as versions are not valid)
("!=1.0", None, None, ["invalid", "foobar"], []),
("!=1.0", None, None, ["1.0", "invalid", "2.0"], ["2.0"]),
("!=2.0.*", None, None, ["invalid", "foobar", "2.0"], []),
("!=2.0.*", None, None, ["1.0", "invalid", "2.0.0"], ["1.0"]),
# Test that !== ignores prereleases parameter for non-PEP 440 versions
("!=1.0", None, True, ["invalid", "foobar"], []),
("!=1.0", None, False, ["invalid", "foobar"], []),
("!=1.0", True, None, ["invalid", "foobar"], []),
("!=1.0", False, None, ["invalid", "foobar"], []),
("!=1.0", True, True, ["invalid", "foobar"], []),
("!=1.0", False, False, ["invalid", "foobar"], []),
# Test that === ignores prereleases parameter for non-PEP 440 versions
("===foobar", None, True, ["foobar", "foo"], ["foobar"]),
("===foobar", None, False, ["foobar", "foo"], ["foobar"]),
("===foobar", True, None, ["foobar", "foo"], ["foobar"]),
("===foobar", False, None, ["foobar", "foo"], ["foobar"]),
("===foobar", True, True, ["foobar", "foo"], ["foobar"]),
("===foobar", False, False, ["foobar", "foo"], ["foobar"]),
],
)
def test_specifier_filter(
self,
specifier: str,
specifier_prereleases: bool | None,
prereleases: bool | None,
input: list[str],
expected: list[str],
) -> None:
if specifier_prereleases is None:
spec = Specifier(specifier)
else:
spec = Specifier(specifier, prereleases=specifier_prereleases)
kwargs = {"prereleases": prereleases} if prereleases is not None else {}
assert list(spec.filter(input, **kwargs)) == expected
@pytest.mark.parametrize(
("spec", "op"),
[
("~=2.0", "~="),
("==2.1.*", "=="),
("==2.1.0.3", "=="),
("!=2.2.*", "!="),
("!=2.2.0.5", "!="),
("<=5", "<="),
(">=7.9a1", ">="),
("<1.0.dev1", "<"),
(">2.0.post1", ">"),
# === is an escape hatch in PEP 440
("===lolwat", "==="),
],
)
def test_specifier_operator_property(self, spec: str, op: str) -> None:
assert Specifier(spec).operator == op
@pytest.mark.parametrize(
("spec", "version"),
[
("~=2.0", "2.0"),
("==2.1.*", "2.1.*"),
("==2.1.0.3", "2.1.0.3"),
("!=2.2.*", "2.2.*"),
("!=2.2.0.5", "2.2.0.5"),
("<=5", "5"),
(">=7.9a1", "7.9a1"),
("<1.0.dev1", "1.0.dev1"),
(">2.0.post1", "2.0.post1"),
# === is an escape hatch in PEP 440
("===lolwat", "lolwat"),
],
)
def test_specifier_version_property(self, spec: str, version: str) -> None:
assert Specifier(spec).version == version
@pytest.mark.parametrize(
("spec_str", "expected_length"),
[("", 0), ("==2.0", 1), (">=2.0", 1), (">=2.0,<3", 2), (">=2.0,<3,==2.4", 3)],
)
def test_length(self, spec_str: str, expected_length: int) -> None:
spec = SpecifierSet(spec_str)
assert len(spec) == expected_length
@pytest.mark.parametrize(
("spec_str", "expected_items"),
[
("", []),
("==2.0", ["==2.0"]),
(">=2.0", [">=2.0"]),
(">=2.0,<3", [">=2.0", "<3"]),
(">=2.0,<3,==2.4", [">=2.0", "<3", "==2.4"]),
],
)
def test_iteration(self, spec_str: str, expected_items: list[str]) -> None:
spec = SpecifierSet(spec_str)
items = {str(item) for item in spec}
assert items == set(expected_items)
def test_specifier_equal_for_compatible_operator(self) -> None:
assert Specifier("~=1.18.0") != Specifier("~=1.18")
def test_specifier_hash_for_compatible_operator(self) -> None:
assert hash(Specifier("~=1.18.0")) != hash(Specifier("~=1.18"))
class TestSpecifierInternal:
"""Tests for internal Specifier._spec_version cache behavior.
Specifier._spec_version is a one-element cache that stores the parsed Version
corresponding to Specifier.version after the first time it is needed for
comparison, these tests validate that the cache is set and never changed.
"""
@pytest.mark.parametrize(
("specifier", "test_versions"),
[
(">=1.0", ["0.9", "1.0", "1.1", "2.0"]),
("<=1.0", ["0.9", "1.0", "1.1", "2.0"]),
(">1.0", ["0.9", "1.0", "1.1", "2.0"]),
("<1.0", ["0.9", "1.0", "1.1", "2.0"]),
("==1.0", ["0.9", "1.0", "1.1", "2.0"]),
("!=1.0", ["0.9", "1.0", "1.1", "2.0"]),
("~=1.0", ["0.9", "1.0", "1.1", "2.0"]),
(">=1.0a1", ["0.9", "1.0a1", "1.0", "1.1"]),
(">=1.0.post1", ["0.9", "1.0", "1.0.post1", "1.1"]),
(">=1.0.dev1", ["0.9", "1.0.dev1", "1.0", "1.1"]),
("==1.0+local", ["1.0", "1.0+local", "1.0+other", "1.1"]),
(">=1!1.0", ["0!2.0", "1!0.9", "1!1.0", "1!1.1"]),
],
)
def test_spec_version_cache_consistency(
self, specifier: str, test_versions: list[str]
) -> None:
"""Cache is set on first contains and remains unchanged."""
spec = Specifier(specifier, prereleases=True)
assert spec._spec_version is None
_ = test_versions[0] in spec
assert spec._spec_version == (spec.version, Version(spec.version))
initial_cache = spec._spec_version
for v in test_versions[1:]:
_ = v in spec
assert spec._spec_version is initial_cache
_ = hash(spec)
assert spec._spec_version is initial_cache
_ = spec.prereleases
assert spec._spec_version is initial_cache
_ = spec == Specifier(specifier)
assert spec._spec_version is initial_cache
@pytest.mark.parametrize(
("specifier", "test_versions"),
[
(
"==1.0.*",
["0.9", "1.0", "1.0.1", "1.0a1", "1.0.dev1", "1.0.post1", "1.0+local"],
),
(
"!=1.0.*",
["0.9", "1.0", "1.0.1", "1.0a1", "1.0.dev1", "1.0.post1", "1.0+local"],
),
],
)
def test_spec_version_cache_with_wildcards(
self, specifier: str, test_versions: list[str]
) -> None:
"""Wildcard specifiers use prefix matching, cache stays None."""
spec = Specifier(specifier, prereleases=True)
for v in test_versions:
_ = v in spec
_ = spec.prereleases
_ = hash(spec)
assert spec._spec_version is None
@pytest.mark.parametrize(
"specifier",
[
"===1.0",
"===1.0.0+local",
"===1.0.dev1",
],
)
def test_spec_version_cache_with_arbitrary_equality(self, specifier: str) -> None:
spec = Specifier(specifier)
_ = "1.0" in spec
_ = spec.prereleases
_ = hash(spec)
assert spec._spec_version == (spec.version, Version(spec.version))
@pytest.mark.parametrize(
("specifier", "versions"),
[
(
"~=1.4.2",
[
# Matching versions
"1.4.2",
"1.4.3.dev1",
"1.4.3a1",
"1.4.3",
"1.4.3.post1",
"1.4.3+local",
# Not matching versions
"1.4.1",
"1.4.1.post1",
"1.5.0.dev0",
"1.5.0a1",
"1.5.0",
"2.0",
"2.0+local",
],
),
],
)
def test_spec_version_cache_compatible_operator(
self,
specifier: str,
versions: list[str],
) -> None:
"""~= caches the original spec version, not the prefix used for ==."""
spec = Specifier(specifier, prereleases=True)
assert spec._spec_version is None
assert versions[0] in spec
assert spec._spec_version == (spec.version, Version(spec.version))
initial_cache = spec._spec_version
for v in versions[1:]:
_ = v in spec
assert spec._spec_version is initial_cache
_ = hash(spec)
assert spec._spec_version is initial_cache
_ = spec.prereleases
assert spec._spec_version is initial_cache
class TestSpecifierSet:
@pytest.mark.parametrize("version", VERSIONS)
def test_empty_specifier(self, version: str) -> None:
spec = SpecifierSet(prereleases=True)
assert version in spec
assert spec.contains(version)
assert parse(version) in spec
assert spec.contains(parse(version))
@pytest.mark.parametrize(
("prereleases", "versions", "expected"),
[
# single arbitrary string
(None, ["foobar"], ["foobar"]),
(False, ["foobar"], ["foobar"]),
(True, ["foobar"], ["foobar"]),
# arbitrary string with a stable version present
(None, ["foobar", "1.0"], ["foobar", "1.0"]),
(False, ["foobar", "1.0"], ["foobar", "1.0"]),
(True, ["foobar", "1.0"], ["foobar", "1.0"]),
# arbitrary string with a prerelease only
(None, ["foobar", "1.0a1"], ["foobar", "1.0a1"]),
(False, ["foobar", "1.0a1"], ["foobar"]),
(True, ["foobar", "1.0a1"], ["foobar", "1.0a1"]),
],
)
def test_empty_specifier_arbitrary_string(
self, prereleases: bool | None, versions: list[str], expected: list[str]
) -> None:
"""Test empty SpecifierSet accepts arbitrary strings."""
spec = SpecifierSet("", prereleases=prereleases)
# basic behavior preserved
assert spec.contains("foobar")
# check filter behavior (no override of prereleases passed to filter)
kwargs: dict[str, bool | None] = {}
assert list(spec.filter(versions, **kwargs)) == expected
def test_create_from_specifiers(self) -> None:
spec_strs = [">=1.0", "!=1.1", "!=1.2", "<2.0"]
specs = [Specifier(s) for s in spec_strs]
spec = SpecifierSet(iter(specs))
assert set(spec) == set(specs)
def test_match_args(self) -> None:
assert SpecifierSet.__match_args__ == ("_str",)
assert SpecifierSet(">=1.0,<2")._str == str(SpecifierSet(">=1.0,<2"))
@pytest.mark.parametrize(
(
"initial_prereleases",
"set_prereleases",
"version",
"initial_contains",
"final_contains",
"spec_str",
),
[
(None, True, "1.0.dev1", True, True, ""),
(False, True, "1.0.dev1", False, True, ""),
# Setting prerelease from True to False
(True, False, "1.0.dev1", True, False, ""),
(True, False, "1.0.dev1", False, False, ">=1.0"),
(True, False, "1.0.dev1", True, False, "==1.*"),
# Setting prerelease from False to None
(False, None, "1.0.dev1", False, True, ""),
(False, None, "2.0.dev1", False, True, ">=1.0"),
# Setting prerelease from True to None
(True, None, "1.0.dev1", True, True, ""),
(True, None, "2.0.dev1", True, True, ">=1.0"),
# Various version patterns with different transitions
(None, True, "2.0b1", True, True, ""),
(None, False, "2.0a1", True, False, ""),
(True, False, "1.0rc1", True, False, ""),
(False, True, "1.0.post1.dev1", False, True, ""),
# Specifiers that include prerelease versions explicitly
(None, False, "2.0.dev1", True, False, "==2.0.dev1"),
(True, False, "1.0.dev1", True, False, "==1.0.*"),
(False, True, "1.0.dev1", False, True, "!=2.0"),
# SpecifierSet with multiple specifiers
(None, True, "1.5a1", True, True, ">=1.0,<2.0"),
(False, True, "1.5b1", False, True, ">=1.0,<2.0"),
(True, False, "1.5rc1", True, False, ">=1.0,<2.0"),
# Test with dev/alpha/beta/rc variations
(None, True, "1.0a1", True, True, ""),
(None, True, "1.0b2", True, True, ""),
(None, True, "1.0rc3", True, True, ""),
(None, True, "1.0.dev4", True, True, ""),
# Test with specifiers that have prereleases implicitly
(None, False, "1.0a1", True, False, ">=1.0a1"),
(None, False, "0.9.dev0", True, False, "<1.0.dev1"),
],
)
def test_specifier_prereleases_explicit(
self,
initial_prereleases: bool | None,
set_prereleases: bool | None,
version: str,
initial_contains: bool,
final_contains: bool,
spec_str: str,
) -> None:
"""Test setting prereleases property with different initial states."""
spec = SpecifierSet(spec_str, prereleases=initial_prereleases)
assert (version in spec) == initial_contains
assert spec.contains(version) == initial_contains
spec.prereleases = set_prereleases
assert (version in spec) == final_contains
assert spec.contains(version) == final_contains
def test_specifier_contains_prereleases(self) -> None:
spec = SpecifierSet()
assert spec.prereleases is None
assert spec.contains("1.0.dev1")
assert spec.contains("1.0.dev1", prereleases=True)
spec = SpecifierSet(prereleases=True)
assert spec.prereleases
assert spec.contains("1.0.dev1")
assert not spec.contains("1.0.dev1", prereleases=False)
@pytest.mark.parametrize(
(
"specifier",
"version",
"spec_prereleases",
"contains_prereleases",
"installed",
"expected",
),
[
("~=1.0", "1.1.0.dev1", None, None, True, True),
("~=1.0", "1.1.0.dev1", False, False, True, True),
("~=1.0", "1.1.0.dev1", True, False, True, True),
("~=1.0", "1.1.0.dev1", None, False, True, True),
# Case when installed=False:
("~=1.0", "1.1.0.dev1", None, True, False, True),
("~=1.0", "1.1.0.dev1", False, True, False, True),
("~=1.0", "1.1.0.dev1", False, False, False, False),
("~=1.0", "1.1.0.dev1", None, False, False, False),
# Test with different version types
("~=1.0", "1.1.0a1", None, None, True, True),
("~=1.0", "1.1.0b1", None, None, True, True),
("~=1.0", "1.1.0rc1", None, None, True, True),
("~=1.0", "1.1.0.post1.dev1", None, None, True, True),
# Test with different specifiers
(">=1.0", "2.0.dev1", None, None, True, True),
("==1.*", "1.5.0a1", None, None, True, True),
(">=1.0,<3.0", "2.0.dev1", None, None, True, True),
("!=2.0", "2.0.dev1", None, None, True, True),
# Test with non-matching versions (regardless of installed)
("~=1.0", "3.0.0.dev1", None, None, True, False),
("~=1.0", "3.0.0.dev1", True, None, True, False),
("~=1.0", "3.0.0.dev1", None, True, True, False),
("~=1.0", "3.0.0.dev1", True, True, True, False),
("~=1.0", "3.0.0.dev1", False, False, True, False),
("~=1.0", "3.0.0.dev1", None, None, False, False),
# Test with versions outside specifier but with prereleases
(">=2.0", "1.9.0.dev1", True, None, True, False),
(">=2.0", "1.9.0.dev1", None, True, True, False),
(">=2.0", "1.9.0.dev1", True, True, True, False),
(">=2.0", "1.9.0.dev1", None, None, False, False),
# Test with edge versions
(">=1.0", "1.0.0.dev1", None, None, True, False),
("<=1.0", "1.0.0.dev1", None, None, True, True),
("<1.0", "1.0.0.dev1", None, None, True, False),
("<1.0", "0.9.0.dev1", None, None, True, True),
# Test with specifiers that have explicit prereleases
(">=1.0.dev1", "1.0.0.dev1", None, None, True, True),
(">=1.0.dev1", "1.0.0.dev1", False, False, False, False),
("==1.0.0.dev1", "1.0.0.dev1", False, False, False, False),
# Test with stable versions
("~=1.0", "1.1.0", None, None, True, True),
("~=1.0", "1.1.0", False, False, False, True),
("~=1.0", "1.1.0", True, False, False, True),
# Test combinations of prereleases=True/False and installed=True/False
("~=1.0", "1.1.0.dev1", True, None, False, True),
("~=1.0", "1.1.0.dev1", False, None, False, False),
# Test conflicting prereleases and contain_prereleases
("~=1.0", "1.1.0.dev1", True, False, False, False),
# Test with specifiers that explicitly have prereleases overridden
(">=1.0.dev1", "1.0.0.dev1", None, False, False, False),
(">=1.0.dev1", "1.0.0.dev1", False, None, False, False),
],
)
def test_specifier_contains_installed_prereleases(
self,
specifier: str,
version: str,
spec_prereleases: bool | None,
contains_prereleases: bool | None,
installed: bool | None,
expected: bool,
) -> None:
"""Test the behavior of SpecifierSet.contains with installed and prereleases."""
spec = SpecifierSet(specifier, prereleases=spec_prereleases)
kwargs = {}
if contains_prereleases is not None:
kwargs["prereleases"] = contains_prereleases
if installed is not None:
kwargs["installed"] = installed
assert spec.contains(version, **kwargs) == expected
spec = SpecifierSet("~=1.0", prereleases=False)
assert spec.contains("1.1.0.dev1", installed=True)
assert not spec.contains("1.1.0.dev1", prereleases=False, installed=False)
@pytest.mark.parametrize(
("specifier", "specifier_prereleases", "prereleases", "input", "expected"),
[
# General test of the filter method
("", None, None, ["1.0", "2.0a1"], ["1.0"]),
(">=1.0.dev1", None, None, ["1.0", "2.0a1"], ["1.0", "2.0a1"]),
("", None, None, ["1.0a1"], ["1.0a1"]),
(">=1.2.3", None, None, ["1.2", "1.5a1"], ["1.5a1"]),
(">=1.2.3", None, None, ["1.3", "1.5a1"], ["1.3"]),
("", None, None, ["1.0", Version("2.0")], ["1.0", Version("2.0")]),
(">=1.0", None, None, ["2.0a1"], ["2.0a1"]),
("!=2.0a1", None, None, ["1.0a2", "1.0", "2.0a1"], ["1.0"]),
("==2.0a1", None, None, ["2.0a1"], ["2.0a1"]),
(">2.0a1", None, None, ["2.0a1", "3.0a2", "3.0"], ["3.0a2", "3.0"]),
("<2.0a1", None, None, ["1.0a2", "1.0", "2.0a1"], ["1.0a2", "1.0"]),
("~=2.0a1", None, None, ["1.0", "2.0a1", "3.0a2", "3.0"], ["2.0a1"]),
# Test overriding with the prereleases parameter on filter
("", None, False, ["1.0a1"], []),
(">=1.0.dev1", None, False, ["1.0", "2.0a1"], ["1.0"]),
("", None, True, ["1.0", "2.0a1"], ["1.0", "2.0a1"]),
# Test overriding with the overall specifier
("", True, None, ["1.0", "2.0a1"], ["1.0", "2.0a1"]),
("", False, None, ["1.0", "2.0a1"], ["1.0"]),
(">=1.0.dev1", True, None, ["1.0", "2.0a1"], ["1.0", "2.0a1"]),
(">=1.0.dev1", False, None, ["1.0", "2.0a1"], ["1.0"]),
("", True, None, ["1.0a1"], ["1.0a1"]),
("", False, None, ["1.0a1"], []),
# Test when both specifier and filter have prerelease value
(">=1.0", True, False, ["1.0", "2.0a1"], ["1.0"]),
(">=1.0", False, True, ["1.0", "2.0a1"], ["1.0", "2.0a1"]),
(">=1.0", True, True, ["1.0", "2.0a1"], ["1.0", "2.0a1"]),
(">=1.0", False, False, ["1.0", "2.0a1"], ["1.0"]),
# Test when there are multiple specifiers
(">=1.0,<=2.0", None, None, ["1.0", "1.5a1"], ["1.0"]),
(">=1.0,<=2.0dev", None, None, ["1.0", "1.5a1"], ["1.0", "1.5a1"]),
(">=1.0,<=2.0", True, None, ["1.0", "1.5a1"], ["1.0", "1.5a1"]),
(">=1.0,<=2.0", False, None, ["1.0", "1.5a1"], ["1.0"]),
(">=1.0,<=2.0dev", False, None, ["1.0", "1.5a1"], ["1.0"]),
(">=1.0,<=2.0dev", True, None, ["1.0", "1.5a1"], ["1.0", "1.5a1"]),
(">=1.0,<=2.0", None, False, ["1.0", "1.5a1"], ["1.0"]),
(">=1.0,<=2.0", None, True, ["1.0", "1.5a1"], ["1.0", "1.5a1"]),
(">=1.0,<=2.0dev", None, False, ["1.0", "1.5a1"], ["1.0"]),
(">=1.0,<=2.0dev", None, True, ["1.0", "1.5a1"], ["1.0", "1.5a1"]),
(">=1.0,<=2.0", True, False, ["1.0", "1.5a1"], ["1.0"]),
(">=1.0,<=2.0", False, True, ["1.0", "1.5a1"], ["1.0", "1.5a1"]),
(">=1.0,<=2.0dev", True, False, ["1.0", "1.5a1"], ["1.0"]),
(">=1.0,<=2.0dev", False, True, ["1.0", "1.5a1"], ["1.0", "1.5a1"]),
# Test that invalid versions are accepted by empty SpecifierSet
("", None, None, ["invalid version"], ["invalid version"]),
("", None, False, ["invalid version"], ["invalid version"]),
("", False, None, ["invalid version"], ["invalid version"]),
("", None, None, ["1.0", "invalid version"], ["1.0", "invalid version"]),
("", None, False, ["1.0", "invalid version"], ["1.0", "invalid version"]),
("", False, None, ["1.0", "invalid version"], ["1.0", "invalid version"]),
# Test arbitrary equality (===)
("===foobar", None, None, ["foobar", "foo", "bar"], ["foobar"]),
("===foobar", None, None, ["foo", "bar"], []),
# Test that === does not match with zero padding
("===1.0", None, None, ["1.0", "1.0.0", "2.0"], ["1.0"]),
# Test that === does not match with local versions
("===1.0", None, None, ["1.0", "1.0+downstream1"], ["1.0"]),
# Test === combined with other operators (arbitrary string)
(">=1.0,===foobar", None, None, ["foobar", "1.0", "2.0"], []),
("!=2.0,===foobar", None, None, ["foobar", "2.0", "bar"], []),
# Test === combined with other operators (version string)
(">=1.0,===1.5", None, None, ["1.0", "1.5", "2.0"], ["1.5"]),
(">=2.0,===1.5", None, None, ["1.0", "1.5", "2.0"], []),
# Test === with mix of valid and invalid versions
(
"===foobar",
None,
None,
["foobar", "1.0", "invalid", "2.0a1"],
["foobar"],
),
("===1.0", None, None, ["1.0", "foobar", "invalid", "1.0.0"], ["1.0"]),
(">=1.0,===1.5", None, None, ["1.5", "foobar", "invalid"], ["1.5"]),
# Test != with invalid versions (should pass through as "not equal")
("!=1.0", None, None, ["invalid", "foobar"], []),
("!=1.0", None, None, ["1.0", "invalid", "2.0"], ["2.0"]),
(
"!=2.0.*",
None,
None,
["invalid", "foobar", "2.0"],
[],
),
("!=2.0.*", None, None, ["1.0", "invalid", "2.0.0"], ["1.0"]),
# Test != with invalid versions combined with other operators
(
"!=1.0,!=2.0",
None,
None,
["invalid", "1.0", "2.0", "3.0"],
["3.0"],
),
(
">=1.0,!=2.0",
None,
None,
["invalid", "1.0", "2.0", "3.0"],
["1.0", "3.0"],
),
# Test that === ignores prereleases parameter for non-PEP 440 versions
("===foobar", None, True, ["foobar", "foo"], ["foobar"]),
("===foobar", None, False, ["foobar", "foo"], ["foobar"]),
("===foobar", True, None, ["foobar", "foo"], ["foobar"]),
("===foobar", False, None, ["foobar", "foo"], ["foobar"]),
("===foobar", True, True, ["foobar", "foo"], ["foobar"]),
("===foobar", False, False, ["foobar", "foo"], ["foobar"]),
],
)
def test_specifier_filter(
self,
specifier: str,
specifier_prereleases: bool | None,
prereleases: bool | None,
input: list[str],
expected: list[str],
) -> None:
if specifier_prereleases is None:
spec = SpecifierSet(specifier)
else:
spec = SpecifierSet(specifier, prereleases=specifier_prereleases)
kwargs = {"prereleases": prereleases} if prereleases is not None else {}
assert list(spec.filter(input, **kwargs)) == expected
@pytest.mark.parametrize(
("specifier", "prereleases", "input", "expected"),
[
# !=1.*, !=2.*, !=3.0 leaves gap at 3.0 prereleases
(
">=1,!=1.*,!=2.*,!=3.0,<=3.0",
None,
["3.0.dev0", "3.0a1"],
["3.0.dev0", "3.0a1"],
),
(
">=1,!=1.*,!=2.*,!=3.0,<=3.0",
None,
["0.9", "3.0.dev0", "3.0a1", "4.0"],
["3.0.dev0", "3.0a1"],
),
(
">=1,!=1.*,!=2.*,!=3.0,<=3.0",
True,
["0.9", "3.0.dev0", "3.0a1", "4.0"],
["3.0.dev0", "3.0a1"],
),
(
">=1,!=1.*,!=2.*,!=3.0,<=3.0",
False,
["0.9", "3.0.dev0", "3.0a1", "4.0"],
[],
),
# >=1.0a1,!=1.*,!=2.*,<3.0 has no matching versions
# because <3.0 excludes 3.0 prereleases
(
">=1.0a1,!=1.*,!=2.*,<3.0",
None,
["1.0a1", "2.0a1", "3.0a1"],
[],
),
(
">=1.0a1,!=1.*,!=2.*,<3.0",
True,
["1.0a1", "2.0a1", "3.0a1"],
[],
),
(
">=1.0a1,!=1.*,!=2.*,<3.0",
False,
["1.0a1", "2.0a1", "3.0a1"],
[],
),
# >=1.0.dev0,!=1.*,!=2.*,<3.0.dev0 has no matching versions
(
">=1.0.dev0,!=1.*,!=2.*,<3.0.dev0",
None,
["1.0.dev0", "2.0.dev0", "3.0.dev0"],
[],
),
(
">=1.0.dev0,!=1.*,!=2.*,<3.0.dev0",
True,
["1.0.dev0", "2.0.dev0", "3.0.dev0"],
[],
),
(
">=1.0.dev0,!=1.*,!=2.*,<3.0.dev0",
False,
["1.0.dev0", "2.0.dev0", "3.0.dev0"],
[],
),
# Gaps with post-releases
(
">=1.0,!=1.0,!=1.1,<2.0",
None,
["1.0.post1", "1.1.post1"],
["1.0.post1", "1.1.post1"],
),
(
">=1.0,!=1.0,!=1.1,<2.0",
None,
["0.9", "1.0.post1", "1.1.post1", "2.0"],
["1.0.post1", "1.1.post1"],
),
(
">=1.0,!=1.0,!=1.1,<2.0",
True,
["0.9", "1.0.post1", "1.1.post1", "2.0"],
["1.0.post1", "1.1.post1"],
),
(
">=1.0,!=1.0,!=1.1,<2.0",
False,
["0.9", "1.0.post1", "1.1.post1", "2.0"],
["1.0.post1", "1.1.post1"],
),
# Dev version gaps
(
">=1,!=1.*,!=2.*,!=3.0,!=3.1,<4",
None,
["3.0.dev0", "3.1.dev0"],
["3.0.dev0", "3.1.dev0"],
),
(
">=1,!=1.*,!=2.*,!=3.0,!=3.1,<4",
None,
["0.5", "3.0.dev0", "3.1.dev0", "5.0"],
["3.0.dev0", "3.1.dev0"],
),
(
">=1,!=1.*,!=2.*,!=3.0,!=3.1,<4",
True,
["0.5", "3.0.dev0", "3.1.dev0", "5.0"],
["3.0.dev0", "3.1.dev0"],
),
(
">=1,!=1.*,!=2.*,!=3.0,!=3.1,<4",
False,
["0.5", "3.0.dev0", "3.1.dev0", "5.0"],
[],
),
# Test that < (exclusive) excludes prereleases of the specified version
# but allows prereleases of earlier versions.
# <1.1 excludes 1.1.dev0, 1.1a1, etc. but allows 1.0a1, 1.0b1
(
">=1.0a1,!=1.0,<1.1",
None,
["1.0a1", "1.0b1"],
["1.0a1", "1.0b1"],
),
(
">=1.0a1,!=1.0,<1.1",
None,
["0.9", "1.0a1", "1.0b1", "1.1"],
["1.0a1", "1.0b1"],
),
(
">=1.0a1,!=1.0,<1.1",
None,
["1.0a1", "1.0b1", "1.1.dev0", "1.1a1"],
["1.0a1", "1.0b1"],
),
(
">=1.0a1,!=1.0,<1.1",
True,
["0.9", "1.0a1", "1.0b1", "1.1"],
["1.0a1", "1.0b1"],
),
(
">=1.0a1,!=1.0,<1.1",
True,
["1.0a1", "1.0b1", "1.1.dev0", "1.1a1"],
["1.0a1", "1.0b1"],
),
(
">=1.0a1,!=1.0,<1.1",
False,
["0.9", "1.0a1", "1.0b1", "1.1"],
[],
),
# Test that <= (inclusive) allows prereleases of the specified version
# when explicitly requested, but follows default prerelease filtering
# when prereleases=None (excludes them if final releases present)
(
">=0.9,!=0.9,<=1.0",
None,
["0.9.post1", "1.0.dev0", "1.0a1", "1.0"],
[
"0.9.post1",
"1.0",
], # prereleases filtered out due to presence of final release
),
(
">=0.9,!=0.9,<=1.0",
None,
["0.9.post1", "1.0.dev0", "1.0a1", "1.0", "1.0.post1"],
[
"0.9.post1",
"1.0",
], # dev/alpha filtered out; post-releases not included with <=
),
(
">=0.9,!=0.9,<=1.0",
True,
["0.9.post1", "1.0.dev0", "1.0a1", "1.0", "1.1"],
[
"0.9.post1",
"1.0.dev0",
"1.0a1",
"1.0",
], # includes prereleases when explicitly True
),
(
">=0.9,!=0.9,<=1.0",
False,
["0.9.post1", "1.0.dev0", "1.0a1", "1.0", "1.1"],
["0.9.post1", "1.0"],
),
# Epoch-based gaps
(
">=1!0,!=1!1.*,!=1!2.*,<1!3",
None,
["1!0.5", "1!2.5"],
["1!0.5"],
),
(
">=1!0,!=1!1.*,!=1!2.*,<1!3",
None,
["0!5.0", "1!0.5", "1!2.5", "2!0.0"],
["1!0.5"],
),
(
">=1!0,!=1!1.*,!=1!2.*,<1!3",
True,
["0!5.0", "1!0.5", "1!2.5", "2!0.0"],
["1!0.5"],
),
(
">=1!0,!=1!1.*,!=1!2.*,<1!3",
False,
["0!5.0", "1!0.5", "1!2.5", "2!0.0"],
["1!0.5"],
),
],
)
def test_filter_exclusionary_bridges(
self,
specifier: str,
prereleases: bool | None,
input: list[str],
expected: list[str],
) -> None:
"""
Test that filter correctly handles exclusionary bridges.
When specifiers exclude certain version ranges (e.g., !=1.*, !=2.*),
there may be "gaps" where only prerelease, dev, or post versions match.
The filter should return these matching versions regardless of whether
non-matching non-prerelease versions are present in the input.
"""
spec = SpecifierSet(specifier)
kwargs = {"prereleases": prereleases} if prereleases is not None else {}
assert list(spec.filter(input, **kwargs)) == expected
@pytest.mark.parametrize(
("specifier", "prereleases", "version", "expected"),
[
# !=1.*, !=2.*, !=3.0 leaves gap at 3.0 prereleases
(">=1,!=1.*,!=2.*,!=3.0,<=3.0", None, "3.0.dev0", True),
(">=1,!=1.*,!=2.*,!=3.0,<=3.0", None, "3.0a1", True),
(">=1,!=1.*,!=2.*,!=3.0,<=3.0", True, "3.0.dev0", True),
(">=1,!=1.*,!=2.*,!=3.0,<=3.0", True, "3.0a1", True),
(">=1,!=1.*,!=2.*,!=3.0,<=3.0", False, "3.0.dev0", False),
(">=1,!=1.*,!=2.*,!=3.0,<=3.0", False, "3.0a1", False),
# Versions outside the gap should not match
(">=1,!=1.*,!=2.*,!=3.0,<=3.0", None, "0.9", False),
(">=1,!=1.*,!=2.*,!=3.0,<=3.0", None, "1.0", False),
(">=1,!=1.*,!=2.*,!=3.0,<=3.0", None, "2.0", False),
(">=1,!=1.*,!=2.*,!=3.0,<=3.0", None, "3.0", False),
(">=1,!=1.*,!=2.*,!=3.0,<=3.0", None, "4.0", False),
# >=1.0a1,!=1.*,!=2.*,<3.0 has no matching versions
# because <3.0 excludes 3.0 prereleases
(">=1.0a1,!=1.*,!=2.*,<3.0", None, "1.0a1", False),
(">=1.0a1,!=1.*,!=2.*,<3.0", None, "2.0a1", False),
(">=1.0a1,!=1.*,!=2.*,<3.0", None, "3.0a1", False),
(">=1.0a1,!=1.*,!=2.*,<3.0", True, "1.0a1", False),
(">=1.0a1,!=1.*,!=2.*,<3.0", True, "2.0a1", False),
(">=1.0a1,!=1.*,!=2.*,<3.0", False, "1.0a1", False),
(">=1.0a1,!=1.*,!=2.*,<3.0", False, "2.0a1", False),
# >=1.0.dev0,!=1.*,!=2.*,<3.0.dev0 has no matching versions
(">=1.0.dev0,!=1.*,!=2.*,<3.0.dev0", None, "1.0.dev0", False),
(">=1.0.dev0,!=1.*,!=2.*,<3.0.dev0", None, "2.0.dev0", False),
(">=1.0.dev0,!=1.*,!=2.*,<3.0.dev0", None, "3.0.dev0", False),
(">=1.0.dev0,!=1.*,!=2.*,<3.0.dev0", True, "1.0.dev0", False),
(">=1.0.dev0,!=1.*,!=2.*,<3.0.dev0", True, "2.0.dev0", False),
(">=1.0.dev0,!=1.*,!=2.*,<3.0.dev0", False, "1.0.dev0", False),
# Gaps with post-releases
(">=1.0,!=1.0,!=1.1,<2.0", None, "1.0.post1", True),
(">=1.0,!=1.0,!=1.1,<2.0", None, "1.1.post1", True),
(">=1.0,!=1.0,!=1.1,<2.0", None, "1.0", False),
(">=1.0,!=1.0,!=1.1,<2.0", None, "1.1", False),
(">=1.0,!=1.0,!=1.1,<2.0", None, "2.0", False),
(">=1.0,!=1.0,!=1.1,<2.0", True, "1.0.post1", True),
(">=1.0,!=1.0,!=1.1,<2.0", True, "1.1.post1", True),
(">=1.0,!=1.0,!=1.1,<2.0", False, "1.0.post1", True),
(">=1.0,!=1.0,!=1.1,<2.0", False, "1.1.post1", True),
# Dev version gaps
(">=1,!=1.*,!=2.*,!=3.0,!=3.1,<4", None, "3.0.dev0", True),
(">=1,!=1.*,!=2.*,!=3.0,!=3.1,<4", None, "3.1.dev0", True),
(">=1,!=1.*,!=2.*,!=3.0,!=3.1,<4", None, "0.5", False),
(">=1,!=1.*,!=2.*,!=3.0,!=3.1,<4", None, "3.0", False),
(">=1,!=1.*,!=2.*,!=3.0,!=3.1,<4", None, "3.1", False),
(">=1,!=1.*,!=2.*,!=3.0,!=3.1,<4", None, "5.0", False),
(">=1,!=1.*,!=2.*,!=3.0,!=3.1,<4", True, "3.0.dev0", True),
(">=1,!=1.*,!=2.*,!=3.0,!=3.1,<4", True, "3.1.dev0", True),
(">=1,!=1.*,!=2.*,!=3.0,!=3.1,<4", False, "3.0.dev0", False),
(">=1,!=1.*,!=2.*,!=3.0,!=3.1,<4", False, "3.1.dev0", False),
# Test that < (exclusive) excludes prereleases of the specified version
# but allows prereleases of earlier versions
(">=1.0a1,!=1.0,<1.1", None, "1.0a1", True),
(">=1.0a1,!=1.0,<1.1", None, "1.0b1", True),
(">=1.0a1,!=1.0,<1.1", None, "0.9", False),
(">=1.0a1,!=1.0,<1.1", None, "1.0", False),
(">=1.0a1,!=1.0,<1.1", None, "1.1", False),
(">=1.0a1,!=1.0,<1.1", None, "1.1.dev0", False),
(">=1.0a1,!=1.0,<1.1", None, "1.1a1", False),
(">=1.0a1,!=1.0,<1.1", True, "1.0a1", True),
(">=1.0a1,!=1.0,<1.1", True, "1.0b1", True),
(">=1.0a1,!=1.0,<1.1", True, "1.1.dev0", False),
(">=1.0a1,!=1.0,<1.1", True, "1.1a1", False),
(">=1.0a1,!=1.0,<1.1", False, "1.0a1", False),
(">=1.0a1,!=1.0,<1.1", False, "1.0b1", False),
# Test that <= (inclusive) allows prereleases of the specified version
# when explicitly requested, but follows default prerelease filtering
(">=0.9,!=0.9,<=1.0", None, "0.9.post1", True),
(">=0.9,!=0.9,<=1.0", None, "1.0", True),
(
">=0.9,!=0.9,<=1.0",
None,
"1.0.dev0",
True,
), # <= allows prereleases of specified version
(
">=0.9,!=0.9,<=1.0",
None,
"1.0a1",
True,
), # <= allows prereleases of specified version
(
">=0.9,!=0.9,<=1.0",
None,
"1.0.post1",
False,
), # 1.0.post1 > 1.0 so excluded by <=1.0
(">=0.9,!=0.9,<=1.0", True, "0.9.post1", True),
(">=0.9,!=0.9,<=1.0", True, "1.0.dev0", True),
(">=0.9,!=0.9,<=1.0", True, "1.0a1", True),
(">=0.9,!=0.9,<=1.0", True, "1.0", True),
(">=0.9,!=0.9,<=1.0", False, "0.9.post1", True),
(">=0.9,!=0.9,<=1.0", False, "1.0.dev0", False),
(">=0.9,!=0.9,<=1.0", False, "1.0a1", False),
(">=0.9,!=0.9,<=1.0", False, "1.0", True),
# Epoch-based gaps
(">=1!0,!=1!1.*,!=1!2.*,<1!3", None, "1!0.5", True),
(">=1!0,!=1!1.*,!=1!2.*,<1!3", None, "1!2.5", False),
(">=1!0,!=1!1.*,!=1!2.*,<1!3", None, "0!5.0", False),
(">=1!0,!=1!1.*,!=1!2.*,<1!3", None, "2!0.0", False),
(">=1!0,!=1!1.*,!=1!2.*,<1!3", True, "1!0.5", True),
(">=1!0,!=1!1.*,!=1!2.*,<1!3", True, "0!5.0", False),
(">=1!0,!=1!1.*,!=1!2.*,<1!3", False, "1!0.5", True),
(">=1!0,!=1!1.*,!=1!2.*,<1!3", False, "0!5.0", False),
],
)
def test_contains_exclusionary_bridges(
self, specifier: str, prereleases: bool | None, version: str, expected: bool
) -> None:
"""
Test that contains correctly handles exclusionary bridges.
When specifiers exclude certain version ranges (e.g., !=1.*, !=2.*),
there may be "gaps" where only prerelease, dev, or post versions match.
The contains method should return True for versions in these gaps
when prereleases=None, following PEP 440 logic.
"""
spec = SpecifierSet(specifier)
kwargs = {"prereleases": prereleases} if prereleases is not None else {}
assert spec.contains(version, **kwargs) == expected
@pytest.mark.parametrize(
("specifier", "input"),
[
(">=1.0", "not a valid version"),
],
)
def test_contains_rejects_invalid_specifier(
self, specifier: str, input: str
) -> None:
spec = SpecifierSet(specifier, prereleases=True)
assert not spec.contains(input)
@pytest.mark.parametrize(
("version", "specifier", "expected"),
[
# Test arbitrary equality (===) with arbitrary strings
("foobar", "===foobar", True),
("foo", "===foobar", False),
("bar", "===foobar", False),
# Test that === does not match with zero padding
("1.0", "===1.0", True),
("1.0.0", "===1.0", False),
# Test that === does not match with local versions
("1.0", "===1.0+downstream1", False),
("1.0+downstream1", "===1.0", False),
# Test === combined with other operators (arbitrary string)
("foobar", "===foobar,!=1.0", False),
("1.0", "===foobar,!=1.0", False),
("foobar", ">=1.0,===foobar", False),
# Test === combined with other operators (version string)
("1.5", ">=1.0,===1.5", True),
("1.5", ">=2.0,===1.5", False), # Doesn't meet >=2.0
("2.5", ">=1.0,===2.5", True),
# Test != with invalid versions (should not pass as not valid versions)
("invalid", "!=1.0", False),
("foobar", "!=1.0", False),
("invalid", "!=2.0.*", False),
# Test != with invalid versions combined with other operators
("invalid", "!=1.0,!=2.0", False),
("foobar", ">=1.0,!=2.0", False),
("1.5", ">=1.0,!=2.0", True),
],
)
def test_contains_arbitrary_equality_contains(
self, version: str, specifier: str, expected: bool
) -> None:
spec = SpecifierSet(specifier)
assert spec.contains(version) == expected
@pytest.mark.parametrize(
("specifier", "expected"),
[
# Single item specifiers should just be reflexive
("!=2.0", "!=2.0"),
("<2.0", "<2.0"),
("<=2.0", "<=2.0"),
("==2.0", "==2.0"),
(">2.0", ">2.0"),
(">=2.0", ">=2.0"),
("~=2.0", "~=2.0"),
# Spaces should be removed
("< 2", "<2"),
# Multiple item specifiers should work
("!=2.0,>1.0", "!=2.0,>1.0"),
("!=2.0 ,>1.0", "!=2.0,>1.0"),
],
)
def test_specifiers_str_and_repr(self, specifier: str, expected: str) -> None:
spec = SpecifierSet(specifier)
assert str(spec) == expected
assert repr(spec) == f""
@pytest.mark.parametrize("specifier", SPECIFIERS + LEGACY_SPECIFIERS)
def test_specifiers_hash(self, specifier: str) -> None:
assert hash(SpecifierSet(specifier)) == hash(SpecifierSet(specifier))
@pytest.mark.parametrize(
("left", "right", "expected"), [(">2.0", "<5.0", ">2.0,<5.0")]
)
def test_specifiers_combine(self, left: str, right: str, expected: str) -> None:
result = SpecifierSet(left) & SpecifierSet(right)
assert result == SpecifierSet(expected)
result = SpecifierSet(left) & right
assert result == SpecifierSet(expected)
result = SpecifierSet(left, prereleases=True) & SpecifierSet(right)
assert result == SpecifierSet(expected)
assert result.prereleases
result = SpecifierSet(left, prereleases=False) & SpecifierSet(right)
assert result == SpecifierSet(expected)
assert not result.prereleases
result = SpecifierSet(left) & SpecifierSet(right, prereleases=True)
assert result == SpecifierSet(expected)
assert result.prereleases
result = SpecifierSet(left) & SpecifierSet(right, prereleases=False)
assert result == SpecifierSet(expected)
assert not result.prereleases
result = SpecifierSet(left, prereleases=True) & SpecifierSet(
right, prereleases=True
)
assert result == SpecifierSet(expected)
assert result.prereleases
result = SpecifierSet(left, prereleases=False) & SpecifierSet(
right, prereleases=False
)
assert result == SpecifierSet(expected)
assert not result.prereleases
with pytest.raises(
ValueError,
match=re.escape(
"Cannot combine SpecifierSets with True and False prerelease overrides."
),
):
result = SpecifierSet(left, prereleases=True) & SpecifierSet(
right, prereleases=False
)
with pytest.raises(
ValueError,
match=re.escape(
"Cannot combine SpecifierSets with True and False prerelease overrides."
),
):
result = SpecifierSet(left, prereleases=False) & SpecifierSet(
right, prereleases=True
)
def test_specifiers_combine_not_implemented(self) -> None:
with pytest.raises(TypeError):
SpecifierSet() & 12 # type: ignore[operator]
@pytest.mark.parametrize(
("left", "right", "op"),
itertools.chain.from_iterable(
# Verify that the equal (==) operator works correctly
[[(x, x, operator.eq) for x in SPECIFIERS]]
+
# Verify that the not equal (!=) operator works correctly
[
[(x, y, operator.ne) for j, y in enumerate(SPECIFIERS) if i != j]
for i, x in enumerate(SPECIFIERS)
]
),
)
def test_comparison_true(
self, left: str, right: str, op: Callable[[object, object], bool]
) -> None:
assert op(SpecifierSet(left), SpecifierSet(right))
assert op(SpecifierSet(left), Specifier(right))
assert op(Specifier(left), SpecifierSet(right))
assert op(left, SpecifierSet(right))
assert op(SpecifierSet(left), right)
@pytest.mark.parametrize(
("left", "right", "op"),
itertools.chain.from_iterable(
# Verify that the equal (==) operator works correctly
[[(x, x, operator.ne) for x in SPECIFIERS]]
+
# Verify that the not equal (!=) operator works correctly
[
[(x, y, operator.eq) for j, y in enumerate(SPECIFIERS) if i != j]
for i, x in enumerate(SPECIFIERS)
]
),
)
def test_comparison_false(
self, left: str, right: str, op: Callable[[object, object], bool]
) -> None:
assert not op(SpecifierSet(left), SpecifierSet(right))
assert not op(SpecifierSet(left), Specifier(right))
assert not op(Specifier(left), SpecifierSet(right))
assert not op(left, SpecifierSet(right))
assert not op(SpecifierSet(left), right)
@pytest.mark.parametrize(("left", "right"), [("==2.8.0", "==2.8")])
def test_comparison_canonicalizes(self, left: str, right: str) -> None:
assert SpecifierSet(left) == SpecifierSet(right)
assert left == SpecifierSet(right)
assert SpecifierSet(left) == right
def test_comparison_non_specifier(self) -> None:
assert SpecifierSet("==1.0") != 12
assert not SpecifierSet("==1.0") == 12
@pytest.mark.parametrize(
("version", "specifier", "expected"),
[
("1.0.0+local", "==1.0.0", True),
("1.0.0+local", "!=1.0.0", False),
("1.0.0+local", "<=1.0.0", True),
("1.0.0+local", ">=1.0.0", True),
("1.0.0+local", "<1.0.0", False),
("1.0.0+local", ">1.0.0", False),
],
)
def test_comparison_ignores_local(
self, version: str, specifier: str, expected: bool
) -> None:
assert (Version(version) in SpecifierSet(specifier)) == expected
def test_contains_with_compatible_operator(self) -> None:
combination = SpecifierSet("~=1.18.0") & SpecifierSet("~=1.18")
assert "1.19.5" not in combination
assert "1.18.0" in combination
@pytest.mark.parametrize(
("spec1", "spec2", "input_versions"),
[
# Test zero padding
("===1.0", "===1.0.0", ["1.0", "1.0.0"]),
("===1.0.0", "===1.0", ["1.0", "1.0.0"]),
("===1.0", "===1.0.0", ["1.0.0", "1.0"]),
("===1.0.0", "===1.0", ["1.0.0", "1.0"]),
# Test local versions
("===1.0", "===1.0+local", ["1.0", "1.0+local"]),
("===1.0+local", "===1.0", ["1.0", "1.0+local"]),
("===1.0", "===1.0+local", ["1.0+local", "1.0"]),
("===1.0+local", "===1.0", ["1.0+local", "1.0"]),
],
)
def test_arbitrary_equality_is_intersection_preserving(
self, spec1: str, spec2: str, input_versions: list[str]
) -> None:
"""
In general we expect for two specifiers s1 and s2, that the two statements
are equivalent:
* set((s1, s2).filter(versions))
* set(s1.filter(versions)) & set(s2.filter(versions)).
This is tricky with the arbitrary equality operator (===) since it does
not follow normal version comparison rules.
"""
s1 = Specifier(spec1)
s2 = Specifier(spec2)
versions1 = set(s1.filter(input_versions))
versions2 = set(s2.filter(input_versions))
combined_versions = set(SpecifierSet(f"{spec1},{spec2}").filter(input_versions))
assert versions1 & versions2 == combined_versions
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1768936045.8193686
packaging-26.0/tests/test_structures.py 0000644 0000000 0000000 00000003223 15133751156 015320 0 ustar 00 # This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import annotations
import pytest
from packaging._structures import Infinity, NegativeInfinity
def test_infinity_repr() -> None:
assert repr(Infinity) == "Infinity"
def test_negative_infinity_repr() -> None:
assert repr(NegativeInfinity) == "-Infinity"
def test_infinity_hash() -> None:
assert hash(Infinity) == hash(Infinity)
def test_negative_infinity_hash() -> None:
assert hash(NegativeInfinity) == hash(NegativeInfinity)
@pytest.mark.parametrize("left", [1, "a", ("b", 4)])
def test_infinity_comparison(left: int | str | tuple[str, int]) -> None:
assert left < Infinity
assert left <= Infinity
assert not left == Infinity
assert left != Infinity
assert not left > Infinity
assert not left >= Infinity
@pytest.mark.parametrize("left", [1, "a", ("b", 4)])
def test_negative_infinity_lesser(left: int | str | tuple[str, int]) -> None:
assert not left < NegativeInfinity
assert not left <= NegativeInfinity
assert not left == NegativeInfinity
assert left != NegativeInfinity
assert left > NegativeInfinity
assert left >= NegativeInfinity
def test_infinity_equal() -> None:
assert Infinity == Infinity
def test_negative_infinity_equal() -> None:
assert NegativeInfinity == NegativeInfinity
def test_negate_infinity() -> None:
assert isinstance(-Infinity, NegativeInfinity.__class__)
def test_negate_negative_infinity() -> None:
assert isinstance(-NegativeInfinity, Infinity.__class__)
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1768936045.8203685
packaging-26.0/tests/test_tags.py 0000644 0000000 0000000 00000203547 15133751156 014046 0 ustar 00 # This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import annotations
import collections.abc
import subprocess
try:
import ctypes
except ImportError:
ctypes = None # type: ignore[assignment]
import importlib
import os
import pathlib
import pickle
import platform
import struct
import sys
import sysconfig
import types
import typing
import pretend
import pytest
from packaging import tags
from packaging._manylinux import _GLibCVersion
from packaging._musllinux import _MuslVersion
if typing.TYPE_CHECKING:
from collections.abc import Callable
@pytest.fixture
def example_tag() -> tags.Tag:
return tags.Tag("py3", "none", "any")
@pytest.fixture
def manylinux_module(monkeypatch: pytest.MonkeyPatch) -> types.ModuleType:
monkeypatch.setattr(tags._manylinux, "_get_glibc_version", lambda *args: (2, 20)) # type: ignore[attr-defined]
module_name = "_manylinux"
module = types.ModuleType(module_name)
monkeypatch.setitem(sys.modules, module_name, module)
return module
@pytest.fixture
def mock_interpreter_name(monkeypatch: pytest.MonkeyPatch) -> Callable[[str], bool]:
def mock(name: str) -> bool:
name = name.lower()
if sys.implementation.name != name:
monkeypatch.setattr(sys.implementation, "name", name)
return True
return False
return mock
@pytest.fixture
def mock_ios(monkeypatch: pytest.MonkeyPatch) -> None:
# Monkeypatch the platform to be iOS
monkeypatch.setattr(sys, "platform", "ios")
# Mock a fake architecture that will fit the expected pattern, but
# won't actually be a legal multiarch.
monkeypatch.setattr(
sys.implementation,
"_multiarch",
"gothic-iphoneos",
raising=False,
)
# Mock the return value of platform.ios_ver.
def mock_ios_ver(*args: object) -> tuple[str, str, str, bool]:
return ("iOS", "13.2", "iPhone15,2", False)
if sys.version_info < (3, 13):
platform.ios_ver = mock_ios_ver # type: ignore[attr-defined]
else:
monkeypatch.setattr(platform, "ios_ver", mock_ios_ver)
@pytest.fixture
def mock_android(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(sys, "platform", "android")
monkeypatch.setattr(platform, "system", lambda: "Android")
monkeypatch.setattr(sysconfig, "get_platform", lambda: "android-21-arm64_v8a")
AndroidVer = collections.namedtuple(
"AndroidVer", "release api_level manufacturer model device is_emulator"
)
monkeypatch.setattr(
platform,
"android_ver",
lambda: AndroidVer("5.0", 21, "Google", "sdk_gphone64_arm64", "emu64a", True),
raising=False, # This function was added in Python 3.13.
)
class TestTag:
def test_lowercasing(self) -> None:
tag = tags.Tag("PY3", "None", "ANY")
assert tag.interpreter == "py3"
assert tag.abi == "none"
assert tag.platform == "any"
def test_equality(self) -> None:
args = "py3", "none", "any"
assert tags.Tag(*args) == tags.Tag(*args)
def test_equality_fails_with_non_tag(self) -> None:
assert not tags.Tag("py3", "none", "any") == "non-tag"
def test_hashing(self, example_tag: tags.Tag) -> None:
tags = {example_tag} # Should not raise TypeError.
assert example_tag in tags
def test_hash_equality(self, example_tag: tags.Tag) -> None:
equal_tag = tags.Tag("py3", "none", "any")
assert example_tag == equal_tag # Sanity check.
assert example_tag.__hash__() == equal_tag.__hash__()
def test_str(self, example_tag: tags.Tag) -> None:
assert str(example_tag) == "py3-none-any"
def test_repr(self, example_tag: tags.Tag) -> None:
assert repr(example_tag) == f""
def test_attribute_access(self, example_tag: tags.Tag) -> None:
assert example_tag.interpreter == "py3"
assert example_tag.abi == "none"
assert example_tag.platform == "any"
class TestParseTag:
def test_simple(self, example_tag: tags.Tag) -> None:
parsed_tags = tags.parse_tag(str(example_tag))
assert parsed_tags == {example_tag}
def test_multi_interpreter(self, example_tag: tags.Tag) -> None:
expected = {example_tag, tags.Tag("py2", "none", "any")}
given = tags.parse_tag("py2.py3-none-any")
assert given == expected
def test_multi_platform(self) -> None:
expected = {
tags.Tag("cp37", "cp37m", platform)
for platform in (
"macosx_10_6_intel",
"macosx_10_9_intel",
"macosx_10_9_x86_64",
"macosx_10_10_intel",
"macosx_10_10_x86_64",
)
}
given = tags.parse_tag(
"cp37-cp37m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64."
"macosx_10_10_intel.macosx_10_10_x86_64"
)
assert given == expected
class TestInterpreterName:
def test_sys_implementation_name(self, monkeypatch: pytest.MonkeyPatch) -> None:
class MockImplementation:
pass
mock_implementation = MockImplementation()
mock_implementation.name = "sillywalk" # type: ignore[attr-defined]
monkeypatch.setattr(sys, "implementation", mock_implementation, raising=False)
assert tags.interpreter_name() == "sillywalk"
def test_interpreter_short_names(
self, mock_interpreter_name: Callable[[str], bool]
) -> None:
mock_interpreter_name("cpython")
assert tags.interpreter_name() == "cp"
class TestInterpreterVersion:
def test_warn(self, monkeypatch: pytest.MonkeyPatch) -> None:
class MockConfigVar:
def __init__(self, return_: str) -> None:
self.warn: bool | None = None
self._return = return_
def __call__(self, _name: str, warn: bool = False) -> str:
self.warn = warn
return self._return
mock_config_var = MockConfigVar("38")
monkeypatch.setattr(tags, "_get_config_var", mock_config_var)
tags.interpreter_version(warn=True)
assert mock_config_var.warn
def test_python_version_nodot(self, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(tags, "_get_config_var", lambda _var, warn: "NN") # noqa: ARG005
assert tags.interpreter_version() == "NN"
@pytest.mark.parametrize(
("version_info", "version_str"),
[
((1, 2, 3), "12"),
((1, 12, 3), "112"),
((11, 2, 3), "112"),
((11, 12, 3), "1112"),
((1, 2, 13), "12"),
],
)
def test_sys_version_info(
self,
version_info: tuple[int, int, int],
version_str: str,
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(tags, "_get_config_var", lambda *args, **kwargs: None)
monkeypatch.setattr(sys, "version_info", version_info)
assert tags.interpreter_version() == version_str
class TestMacOSPlatforms:
@pytest.mark.parametrize(
("arch", "is_32bit", "expected"),
[
("i386", True, "i386"),
("ppc", True, "ppc"),
("x86_64", False, "x86_64"),
("x86_64", True, "i386"),
("ppc64", False, "ppc64"),
("ppc64", True, "ppc"),
],
)
def test_architectures(self, arch: str, is_32bit: bool, expected: str) -> None:
assert tags._mac_arch(arch, is_32bit=is_32bit) == expected
@pytest.mark.parametrize(
("version", "arch", "expected"),
[
(
(10, 15),
"x86_64",
["x86_64", "intel", "fat64", "fat32", "universal2", "universal"],
),
(
(10, 4),
"x86_64",
["x86_64", "intel", "fat64", "fat32", "universal2", "universal"],
),
((10, 3), "x86_64", []),
((10, 15), "i386", ["i386", "intel", "fat32", "fat", "universal"]),
((10, 4), "i386", ["i386", "intel", "fat32", "fat", "universal"]),
((10, 3), "intel", ["intel", "universal"]),
((10, 5), "intel", ["intel", "universal"]),
((10, 15), "intel", ["intel", "universal"]),
((10, 3), "i386", []),
((10, 15), "ppc64", []),
((10, 6), "ppc64", []),
((10, 5), "ppc64", ["ppc64", "fat64", "universal"]),
((10, 3), "ppc64", []),
((10, 15), "ppc", []),
((10, 7), "ppc", []),
((10, 6), "ppc", ["ppc", "fat32", "fat", "universal"]),
((10, 0), "ppc", ["ppc", "fat32", "fat", "universal"]),
((11, 0), "riscv", ["riscv"]),
(
(11, 0),
"x86_64",
["x86_64", "intel", "fat64", "fat32", "universal2", "universal"],
),
((11, 0), "arm64", ["arm64", "universal2"]),
((11, 1), "arm64", ["arm64", "universal2"]),
((12, 0), "arm64", ["arm64", "universal2"]),
],
)
def test_binary_formats(
self, version: tuple[int, int], arch: str, expected: list[str]
) -> None:
assert tags._mac_binary_formats(version, arch) == expected
def test_version_detection(self, monkeypatch: pytest.MonkeyPatch) -> None:
if platform.system() != "Darwin":
monkeypatch.setattr(
platform, "mac_ver", lambda: ("10.14", ("", "", ""), "x86_64")
)
version = platform.mac_ver()[0].split(".")
major = version[0]
minor = version[1] if major == "10" else "0"
platforms = list(tags.mac_platforms(arch="x86_64"))
if (major, minor) == ("10", "16"):
# For 10.16, the real version is at least 11.0.
prefix, major, minor, _ = platforms[0].split("_", maxsplit=3)
assert prefix == "macosx"
assert int(major) >= 11
assert minor == "0"
else:
expected = f"macosx_{major}_{minor}_"
assert platforms[0].startswith(expected)
def test_version_detection_10_15(self, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(
platform, "mac_ver", lambda: ("10.15", ("", "", ""), "x86_64")
)
expected = "macosx_10_15_"
platforms = list(tags.mac_platforms(arch="x86_64"))
assert platforms[0].startswith(expected)
def test_version_detection_compatibility(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
if platform.system() != "Darwin":
monkeypatch.setattr(
subprocess,
"run",
lambda *args, **kwargs: subprocess.CompletedProcess(
[], 0, stdout="10.15"
),
)
monkeypatch.setattr(
platform, "mac_ver", lambda: ("10.16", ("", "", ""), "x86_64")
)
unexpected = "macosx_10_16_"
platforms = list(tags.mac_platforms(arch="x86_64"))
assert not platforms[0].startswith(unexpected)
@pytest.mark.parametrize("arch", ["x86_64", "i386"])
def test_arch_detection(self, arch: str, monkeypatch: pytest.MonkeyPatch) -> None:
if platform.system() != "Darwin" or platform.mac_ver()[2] != arch:
monkeypatch.setattr(
platform, "mac_ver", lambda: ("10.14", ("", "", ""), arch)
)
monkeypatch.setattr(tags, "_mac_arch", lambda *args: arch)
assert next(tags.mac_platforms((10, 14))).endswith(arch)
def test_mac_platforms(self) -> None:
platforms = list(tags.mac_platforms((10, 5), "x86_64"))
assert platforms == [
"macosx_10_5_x86_64",
"macosx_10_5_intel",
"macosx_10_5_fat64",
"macosx_10_5_fat32",
"macosx_10_5_universal2",
"macosx_10_5_universal",
"macosx_10_4_x86_64",
"macosx_10_4_intel",
"macosx_10_4_fat64",
"macosx_10_4_fat32",
"macosx_10_4_universal2",
"macosx_10_4_universal",
]
assert len(list(tags.mac_platforms((10, 17), "x86_64"))) == 14 * 6
assert not list(tags.mac_platforms((10, 0), "x86_64"))
@pytest.mark.parametrize(("major", "minor"), [(11, 0), (11, 3), (12, 0), (12, 3)])
def test_macos_11(self, major: int, minor: int) -> None:
platforms = list(tags.mac_platforms((major, minor), "x86_64"))
assert "macosx_11_0_arm64" not in platforms
assert "macosx_11_0_x86_64" in platforms
assert "macosx_11_3_x86_64" not in platforms
assert "macosx_11_0_universal" in platforms
assert "macosx_11_0_universal2" in platforms
# Mac OS "10.16" is the version number that binaries compiled against an old
# (pre 11.0) SDK will see. It can also be enabled explicitly for a process
# with the environment variable SYSTEM_VERSION_COMPAT=1.
assert "macosx_10_16_x86_64" in platforms
assert "macosx_10_15_x86_64" in platforms
assert "macosx_10_15_universal2" in platforms
assert "macosx_10_4_x86_64" in platforms
assert "macosx_10_3_x86_64" not in platforms
if major >= 12:
assert "macosx_12_0_x86_64" in platforms
assert "macosx_12_0_universal" in platforms
assert "macosx_12_0_universal2" in platforms
platforms = list(tags.mac_platforms((major, minor), "arm64"))
assert "macosx_11_0_arm64" in platforms
assert "macosx_11_3_arm64" not in platforms
assert "macosx_11_0_universal" not in platforms
assert "macosx_11_0_universal2" in platforms
assert "macosx_10_15_universal2" in platforms
assert "macosx_10_15_x86_64" not in platforms
assert "macosx_10_4_x86_64" not in platforms
assert "macosx_10_3_x86_64" not in platforms
if major >= 12:
assert "macosx_12_0_arm64" in platforms
assert "macosx_12_0_universal2" in platforms
class TestIOSPlatforms:
@pytest.mark.usefixtures("mock_ios")
def test_version_detection(self) -> None:
platforms = list(tags.ios_platforms(multiarch="arm64-iphoneos"))
assert platforms == [
"ios_13_2_arm64_iphoneos",
"ios_13_1_arm64_iphoneos",
"ios_13_0_arm64_iphoneos",
"ios_12_9_arm64_iphoneos",
"ios_12_8_arm64_iphoneos",
"ios_12_7_arm64_iphoneos",
"ios_12_6_arm64_iphoneos",
"ios_12_5_arm64_iphoneos",
"ios_12_4_arm64_iphoneos",
"ios_12_3_arm64_iphoneos",
"ios_12_2_arm64_iphoneos",
"ios_12_1_arm64_iphoneos",
"ios_12_0_arm64_iphoneos",
]
@pytest.mark.usefixtures("mock_ios")
def test_multiarch_detection(self) -> None:
platforms = list(tags.ios_platforms(version=(12, 0)))
assert platforms == ["ios_12_0_gothic_iphoneos"]
@pytest.mark.usefixtures("mock_ios")
def test_ios_platforms(self) -> None:
# Pre-iOS 12.0 releases won't match anything
platforms = list(tags.ios_platforms((7, 0), "arm64-iphoneos"))
assert platforms == []
# iOS 12.0 returns exactly 1 match
platforms = list(tags.ios_platforms((12, 0), "arm64-iphoneos"))
assert platforms == ["ios_12_0_arm64_iphoneos"]
# iOS 13.0 returns a match for 13.0, plus every 12.X
platforms = list(tags.ios_platforms((13, 0), "x86_64-iphonesimulator"))
assert platforms == [
"ios_13_0_x86_64_iphonesimulator",
"ios_12_9_x86_64_iphonesimulator",
"ios_12_8_x86_64_iphonesimulator",
"ios_12_7_x86_64_iphonesimulator",
"ios_12_6_x86_64_iphonesimulator",
"ios_12_5_x86_64_iphonesimulator",
"ios_12_4_x86_64_iphonesimulator",
"ios_12_3_x86_64_iphonesimulator",
"ios_12_2_x86_64_iphonesimulator",
"ios_12_1_x86_64_iphonesimulator",
"ios_12_0_x86_64_iphonesimulator",
]
# iOS 14.3 returns a match for 14.3-14.0, plus every 13.X and every 12.X
platforms = list(tags.ios_platforms((14, 3), "arm64-iphoneos"))
assert platforms == [
"ios_14_3_arm64_iphoneos",
"ios_14_2_arm64_iphoneos",
"ios_14_1_arm64_iphoneos",
"ios_14_0_arm64_iphoneos",
"ios_13_9_arm64_iphoneos",
"ios_13_8_arm64_iphoneos",
"ios_13_7_arm64_iphoneos",
"ios_13_6_arm64_iphoneos",
"ios_13_5_arm64_iphoneos",
"ios_13_4_arm64_iphoneos",
"ios_13_3_arm64_iphoneos",
"ios_13_2_arm64_iphoneos",
"ios_13_1_arm64_iphoneos",
"ios_13_0_arm64_iphoneos",
"ios_12_9_arm64_iphoneos",
"ios_12_8_arm64_iphoneos",
"ios_12_7_arm64_iphoneos",
"ios_12_6_arm64_iphoneos",
"ios_12_5_arm64_iphoneos",
"ios_12_4_arm64_iphoneos",
"ios_12_3_arm64_iphoneos",
"ios_12_2_arm64_iphoneos",
"ios_12_1_arm64_iphoneos",
"ios_12_0_arm64_iphoneos",
]
class TestAndroidPlatforms:
def test_non_android(self) -> None:
non_android_error = pytest.raises(TypeError)
with non_android_error:
list(tags.android_platforms())
with non_android_error:
list(tags.android_platforms(api_level=18))
with non_android_error:
list(tags.android_platforms(abi="x86_64"))
# The function can only be called on non-Android platforms if both arguments are
# provided.
assert list(tags.android_platforms(api_level=18, abi="x86_64")) == [
"android_18_x86_64",
"android_17_x86_64",
"android_16_x86_64",
]
@pytest.mark.usefixtures("mock_android")
def test_detection(self) -> None:
assert list(tags.android_platforms()) == [
"android_21_arm64_v8a",
"android_20_arm64_v8a",
"android_19_arm64_v8a",
"android_18_arm64_v8a",
"android_17_arm64_v8a",
"android_16_arm64_v8a",
]
def test_api_level(self) -> None:
# API levels below the minimum should return nothing.
assert list(tags.android_platforms(api_level=14, abi="x86")) == []
assert list(tags.android_platforms(api_level=15, abi="x86")) == []
assert list(tags.android_platforms(api_level=16, abi="x86")) == [
"android_16_x86",
]
assert list(tags.android_platforms(api_level=17, abi="x86")) == [
"android_17_x86",
"android_16_x86",
]
assert list(tags.android_platforms(api_level=18, abi="x86")) == [
"android_18_x86",
"android_17_x86",
"android_16_x86",
]
def test_abi(self) -> None:
# Real ABI, normalized.
assert list(tags.android_platforms(api_level=16, abi="armeabi_v7a")) == [
"android_16_armeabi_v7a",
]
# Real ABI, not normalized.
assert list(tags.android_platforms(api_level=16, abi="armeabi-v7a")) == [
"android_16_armeabi_v7a",
]
# Nonexistent ABIs should still be accepted and normalized.
assert list(tags.android_platforms(api_level=16, abi="myarch-4.2")) == [
"android_16_myarch_4_2",
]
class TestManylinuxPlatform:
def teardown_method(self) -> None:
# Clear the version cache
tags._manylinux._get_glibc_version.cache_clear() # type: ignore[attr-defined]
def test_get_config_var_does_not_log(self, monkeypatch: pytest.MonkeyPatch) -> None:
debug = pretend.call_recorder(lambda *a: None)
monkeypatch.setattr(tags.logger, "debug", debug)
tags._get_config_var("missing")
assert debug.calls == []
def test_get_config_var_does_log(self, monkeypatch: pytest.MonkeyPatch) -> None:
debug = pretend.call_recorder(lambda *a: None)
monkeypatch.setattr(tags.logger, "debug", debug)
tags._get_config_var("missing", warn=True)
assert debug.calls == [
pretend.call(
"Config variable '%s' is unset, Python ABI tag may be incorrect",
"missing",
)
]
@pytest.mark.parametrize(
("arch", "is_32bit", "expected"),
[
("linux-x86_64", False, ["linux_x86_64"]),
("linux-x86_64", True, ["linux_i686"]),
("linux-aarch64", False, ["linux_aarch64"]),
("linux-aarch64", True, ["linux_armv8l", "linux_armv7l"]),
],
)
def test_linux_platforms_32_64bit_on_64bit_os(
self,
arch: str,
is_32bit: bool,
expected: list[str],
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(sysconfig, "get_platform", lambda: arch)
monkeypatch.setattr(os, "confstr", lambda _: "glibc 2.20", raising=False)
monkeypatch.setattr(tags._manylinux, "_is_compatible", lambda *args: False) # type: ignore[attr-defined]
linux_platform = list(tags._linux_platforms(is_32bit=is_32bit))[
-len(expected) :
]
assert linux_platform == expected
def test_linux_platforms_manylinux_unsupported(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr(sysconfig, "get_platform", lambda: "linux_x86_64")
monkeypatch.setattr(os, "confstr", lambda _: "glibc 2.20", raising=False)
monkeypatch.setattr(tags._manylinux, "_is_compatible", lambda *args: False) # type: ignore[attr-defined]
linux_platform = list(tags._linux_platforms(is_32bit=False))
assert linux_platform == ["linux_x86_64"]
def test_linux_platforms_manylinux1(self, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(
tags._manylinux, # type: ignore[attr-defined]
"_is_compatible",
lambda _, glibc_version: glibc_version == _GLibCVersion(2, 5),
)
monkeypatch.setattr(sysconfig, "get_platform", lambda: "linux_x86_64")
monkeypatch.setattr(platform, "machine", lambda: "x86_64")
monkeypatch.setattr(os, "confstr", lambda _: "glibc 2.20", raising=False)
platforms = list(tags._linux_platforms(is_32bit=False))
assert platforms == [
"manylinux_2_5_x86_64",
"manylinux1_x86_64",
"linux_x86_64",
]
def test_linux_platforms_manylinux2010(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr(sysconfig, "get_platform", lambda: "linux_x86_64")
monkeypatch.setattr(platform, "machine", lambda: "x86_64")
monkeypatch.setattr(os, "confstr", lambda _: "glibc 2.12", raising=False)
platforms = list(tags._linux_platforms(is_32bit=False))
expected = [
"manylinux_2_12_x86_64",
"manylinux2010_x86_64",
"manylinux_2_11_x86_64",
"manylinux_2_10_x86_64",
"manylinux_2_9_x86_64",
"manylinux_2_8_x86_64",
"manylinux_2_7_x86_64",
"manylinux_2_6_x86_64",
"manylinux_2_5_x86_64",
"manylinux1_x86_64",
"linux_x86_64",
]
assert platforms == expected
def test_linux_platforms_manylinux2014(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr(sysconfig, "get_platform", lambda: "linux_x86_64")
monkeypatch.setattr(platform, "machine", lambda: "x86_64")
monkeypatch.setattr(os, "confstr", lambda _: "glibc 2.17", raising=False)
platforms = list(tags._linux_platforms(is_32bit=False))
arch = platform.machine()
expected = [
"manylinux_2_17_" + arch,
"manylinux2014_" + arch,
"manylinux_2_16_" + arch,
"manylinux_2_15_" + arch,
"manylinux_2_14_" + arch,
"manylinux_2_13_" + arch,
"manylinux_2_12_" + arch,
"manylinux2010_" + arch,
"manylinux_2_11_" + arch,
"manylinux_2_10_" + arch,
"manylinux_2_9_" + arch,
"manylinux_2_8_" + arch,
"manylinux_2_7_" + arch,
"manylinux_2_6_" + arch,
"manylinux_2_5_" + arch,
"manylinux1_" + arch,
"linux_" + arch,
]
assert platforms == expected
@pytest.mark.parametrize(
("native_arch", "cross_arch"),
[("armv7l", "armv7l"), ("armv8l", "armv8l"), ("aarch64", "armv8l")],
)
def test_linux_platforms_manylinux2014_armhf_abi(
self, native_arch: str, cross_arch: str, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr(tags._manylinux, "_glibc_version_string", lambda: "2.30") # type: ignore[attr-defined]
monkeypatch.setattr(
tags._manylinux, # type: ignore[attr-defined]
"_is_compatible",
lambda _, glibc_version: glibc_version == _GLibCVersion(2, 17),
)
monkeypatch.setattr(sysconfig, "get_platform", lambda: f"linux_{native_arch}")
monkeypatch.setattr(
sys,
"executable",
os.path.join(
os.path.dirname(__file__),
"manylinux",
"hello-world-armv7l-armhf",
),
)
platforms = list(tags._linux_platforms(is_32bit=True))
archs = {"armv8l": ["armv8l", "armv7l"]}.get(cross_arch, [cross_arch])
expected = []
for arch in archs:
expected.extend([f"manylinux_2_17_{arch}", f"manylinux2014_{arch}"])
expected.extend(f"linux_{arch}" for arch in archs)
assert platforms == expected
def test_linux_platforms_manylinux2014_i386_abi(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr(tags._manylinux, "_glibc_version_string", lambda: "2.17") # type: ignore[attr-defined]
monkeypatch.setattr(sysconfig, "get_platform", lambda: "linux_x86_64")
monkeypatch.setattr(
sys,
"executable",
os.path.join(
os.path.dirname(__file__),
"manylinux",
"hello-world-x86_64-i386",
),
)
platforms = list(tags._linux_platforms(is_32bit=True))
expected = [
"manylinux_2_17_i686",
"manylinux2014_i686",
"manylinux_2_16_i686",
"manylinux_2_15_i686",
"manylinux_2_14_i686",
"manylinux_2_13_i686",
"manylinux_2_12_i686",
"manylinux2010_i686",
"manylinux_2_11_i686",
"manylinux_2_10_i686",
"manylinux_2_9_i686",
"manylinux_2_8_i686",
"manylinux_2_7_i686",
"manylinux_2_6_i686",
"manylinux_2_5_i686",
"manylinux1_i686",
"linux_i686",
]
assert platforms == expected
def test_linux_platforms_manylinux_glibc3(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
# test for a future glic 3.x version
monkeypatch.setattr(tags._manylinux, "_glibc_version_string", lambda: "3.2") # type: ignore[attr-defined]
monkeypatch.setattr(tags._manylinux, "_is_compatible", lambda *args: True) # type: ignore[attr-defined]
monkeypatch.setattr(sysconfig, "get_platform", lambda: "linux_aarch64")
monkeypatch.setattr(
sys,
"executable",
os.path.join(
os.path.dirname(__file__),
"manylinux",
"hello-world-aarch64",
),
)
platforms = list(tags._linux_platforms(is_32bit=False))
expected = (
["manylinux_3_2_aarch64", "manylinux_3_1_aarch64", "manylinux_3_0_aarch64"]
+ [f"manylinux_2_{i}_aarch64" for i in range(50, 16, -1)]
+ ["manylinux2014_aarch64", "linux_aarch64"]
)
assert platforms == expected
@pytest.mark.parametrize(
("native_arch", "cross32_arch", "musl_version"),
[
("armv7l", "armv7l", _MuslVersion(1, 1)),
("aarch64", "armv8l", _MuslVersion(1, 1)),
("i386", "i386", _MuslVersion(1, 2)),
("x86_64", "i686", _MuslVersion(1, 2)),
],
)
@pytest.mark.parametrize("cross32", [True, False], ids=["cross", "native"])
def test_linux_platforms_musllinux(
self,
monkeypatch: pytest.MonkeyPatch,
native_arch: str,
cross32_arch: str,
musl_version: _MuslVersion,
cross32: bool,
) -> None:
fake_executable = str(
pathlib.Path(__file__)
.parent.joinpath("musllinux", f"musl-{native_arch}")
.resolve()
)
monkeypatch.setattr(tags._musllinux.sys, "executable", fake_executable) # type: ignore[attr-defined]
monkeypatch.setattr(sysconfig, "get_platform", lambda: f"linux_{native_arch}")
monkeypatch.setattr(tags._manylinux, "platform_tags", lambda *_: ()) # type: ignore[attr-defined]
recorder = pretend.call_recorder(lambda _: musl_version)
monkeypatch.setattr(tags._musllinux, "_get_musl_version", recorder) # type: ignore[attr-defined]
platforms = list(tags._linux_platforms(is_32bit=cross32))
target_arch = cross32_arch if cross32 else native_arch
archs = {"armv8l": ["armv8l", "armv7l"]}.get(target_arch, [target_arch])
expected: list[str] = []
for arch in archs:
expected.extend(
f"musllinux_{musl_version[0]}_{minor}_{arch}"
for minor in range(musl_version[1], -1, -1)
)
expected.extend(f"linux_{arch}" for arch in archs)
assert platforms == expected
assert recorder.calls == [pretend.call(fake_executable)]
def test_linux_platforms_manylinux2014_armv6l(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr(
tags._manylinux, # type: ignore[attr-defined]
"_is_compatible",
lambda _, glibc_version: glibc_version == _GLibCVersion(2, 17),
)
monkeypatch.setattr(sysconfig, "get_platform", lambda: "linux_armv6l")
monkeypatch.setattr(os, "confstr", lambda _: "glibc 2.20", raising=False)
platforms = list(tags._linux_platforms(is_32bit=True))
expected = ["linux_armv6l"]
assert platforms == expected
@pytest.mark.parametrize(
("machine", "abi", "alt_machine"),
[("x86_64", "x32", "i686"), ("armv7l", "armel", "armv7l")],
)
def test_linux_platforms_not_manylinux_abi(
self, monkeypatch: pytest.MonkeyPatch, machine: str, abi: str, alt_machine: str
) -> None:
monkeypatch.setattr(tags._manylinux, "_is_compatible", lambda *args: False) # type: ignore[attr-defined]
monkeypatch.setattr(sysconfig, "get_platform", lambda: f"linux_{machine}")
monkeypatch.setattr(
sys,
"executable",
os.path.join(
os.path.dirname(__file__),
"manylinux",
f"hello-world-{machine}-{abi}",
),
)
platforms = list(tags._linux_platforms(is_32bit=True))
expected = [f"linux_{alt_machine}"]
assert platforms == expected
def test_linux_not_linux(self, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(sysconfig, "get_platform", lambda: "not_linux_x86_64")
monkeypatch.setattr(platform, "machine", lambda: "x86_64")
monkeypatch.setattr(os, "confstr", lambda _: "glibc 2.17", raising=False)
platforms = list(tags._linux_platforms(is_32bit=False))
assert platforms == ["not_linux_x86_64"]
@pytest.mark.parametrize(
("platform_name", "dispatch_func"),
[
("Darwin", "mac_platforms"),
("iOS", "ios_platforms"),
("Android", "android_platforms"),
("Linux", "_linux_platforms"),
("Generic", "_generic_platforms"),
],
)
def test_platform_tags(
platform_name: str, dispatch_func: str, monkeypatch: pytest.MonkeyPatch
) -> None:
expected = ["sillywalk"]
monkeypatch.setattr(platform, "system", lambda: platform_name)
monkeypatch.setattr(tags, dispatch_func, lambda: expected)
assert list(tags.platform_tags()) == expected
def test_platform_tags_space(monkeypatch: pytest.MonkeyPatch) -> None:
"""Ensure spaces in platform tags are normalized to underscores."""
monkeypatch.setattr(platform, "system", lambda: "Isilon OneFS")
monkeypatch.setattr(sysconfig, "get_platform", lambda: "isilon onefs")
assert list(tags.platform_tags()) == ["isilon_onefs"]
class TestCPythonABI:
@pytest.mark.parametrize(
("py_debug", "gettotalrefcount", "result"),
[(1, False, True), (0, False, False), (None, True, True)],
)
def test_debug(
self,
py_debug: int | None,
gettotalrefcount: bool,
result: bool,
monkeypatch: pytest.MonkeyPatch,
) -> None:
config = {"Py_DEBUG": py_debug, "WITH_PYMALLOC": 0, "Py_UNICODE_SIZE": 2}
monkeypatch.setattr(sysconfig, "get_config_var", config.__getitem__)
if gettotalrefcount:
monkeypatch.setattr(sys, "gettotalrefcount", 1, raising=False)
expected = ["cp37d" if result else "cp37"]
assert tags._cpython_abis((3, 7)) == expected
def test_debug_file_extension(self, monkeypatch: pytest.MonkeyPatch) -> None:
config = {"Py_DEBUG": None}
monkeypatch.setattr(sysconfig, "get_config_var", config.__getitem__)
monkeypatch.delattr(sys, "gettotalrefcount", raising=False)
monkeypatch.setattr(tags, "EXTENSION_SUFFIXES", {"_d.pyd"})
assert tags._cpython_abis((3, 8)) == ["cp38d", "cp38"]
@pytest.mark.parametrize(
("debug", "expected"), [(True, ["cp38d", "cp38"]), (False, ["cp38"])]
)
def test__debug_cp38(
self, debug: int | None, expected: list[str], monkeypatch: pytest.MonkeyPatch
) -> None:
config = {"Py_DEBUG": debug}
monkeypatch.setattr(sysconfig, "get_config_var", config.__getitem__)
assert tags._cpython_abis((3, 8)) == expected
@pytest.mark.parametrize(
("pymalloc", "version", "result"),
[
(1, (3, 7), True),
(0, (3, 7), False),
(None, (3, 7), True),
(1, (3, 8), False),
],
)
def test_pymalloc(
self,
pymalloc: int | None,
version: tuple[int, int],
result: bool,
monkeypatch: pytest.MonkeyPatch,
) -> None:
config = {"Py_DEBUG": 0, "WITH_PYMALLOC": pymalloc, "Py_UNICODE_SIZE": 2}
monkeypatch.setattr(sysconfig, "get_config_var", config.__getitem__)
base_abi = f"cp{version[0]}{version[1]}"
expected = [base_abi + "m" if result else base_abi]
assert tags._cpython_abis(version) == expected
@pytest.mark.parametrize(
("unicode_size", "maxunicode", "version", "result"),
[
(4, 0x10FFFF, (3, 2), True),
(2, 0xFFFF, (3, 2), False),
(None, 0x10FFFF, (3, 2), True),
(None, 0xFFFF, (3, 2), False),
(4, 0x10FFFF, (3, 3), False),
],
)
def test_wide_unicode(
self,
unicode_size: int | None,
maxunicode: int,
version: tuple[int, int],
result: bool,
monkeypatch: pytest.MonkeyPatch,
) -> None:
config = {"Py_DEBUG": 0, "WITH_PYMALLOC": 0, "Py_UNICODE_SIZE": unicode_size}
monkeypatch.setattr(sysconfig, "get_config_var", config.__getitem__)
monkeypatch.setattr(sys, "maxunicode", maxunicode)
base_abi = "cp" + tags._version_nodot(version)
expected = [base_abi + "u" if result else base_abi]
assert tags._cpython_abis(version) == expected
class TestCPythonTags:
def test_iterator_returned(self) -> None:
result_iterator = tags.cpython_tags(
(3, 8), ["cp38d", "cp38"], ["plat1", "plat2"]
)
assert isinstance(result_iterator, collections.abc.Iterator)
def test_all_args(self) -> None:
result_iterator = tags.cpython_tags(
(3, 11), ["cp311d", "cp311"], ["plat1", "plat2"]
)
result = list(result_iterator)
assert result == [
tags.Tag("cp311", "cp311d", "plat1"),
tags.Tag("cp311", "cp311d", "plat2"),
tags.Tag("cp311", "cp311", "plat1"),
tags.Tag("cp311", "cp311", "plat2"),
tags.Tag("cp311", "abi3", "plat1"),
tags.Tag("cp311", "abi3", "plat2"),
tags.Tag("cp311", "none", "plat1"),
tags.Tag("cp311", "none", "plat2"),
tags.Tag("cp310", "abi3", "plat1"),
tags.Tag("cp310", "abi3", "plat2"),
tags.Tag("cp39", "abi3", "plat1"),
tags.Tag("cp39", "abi3", "plat2"),
tags.Tag("cp38", "abi3", "plat1"),
tags.Tag("cp38", "abi3", "plat2"),
tags.Tag("cp37", "abi3", "plat1"),
tags.Tag("cp37", "abi3", "plat2"),
tags.Tag("cp36", "abi3", "plat1"),
tags.Tag("cp36", "abi3", "plat2"),
tags.Tag("cp35", "abi3", "plat1"),
tags.Tag("cp35", "abi3", "plat2"),
tags.Tag("cp34", "abi3", "plat1"),
tags.Tag("cp34", "abi3", "plat2"),
tags.Tag("cp33", "abi3", "plat1"),
tags.Tag("cp33", "abi3", "plat2"),
tags.Tag("cp32", "abi3", "plat1"),
tags.Tag("cp32", "abi3", "plat2"),
]
result_iterator = tags.cpython_tags(
(3, 8), ["cp38d", "cp38"], ["plat1", "plat2"]
)
result = list(result_iterator)
assert result == [
tags.Tag("cp38", "cp38d", "plat1"),
tags.Tag("cp38", "cp38d", "plat2"),
tags.Tag("cp38", "cp38", "plat1"),
tags.Tag("cp38", "cp38", "plat2"),
tags.Tag("cp38", "abi3", "plat1"),
tags.Tag("cp38", "abi3", "plat2"),
tags.Tag("cp38", "none", "plat1"),
tags.Tag("cp38", "none", "plat2"),
tags.Tag("cp37", "abi3", "plat1"),
tags.Tag("cp37", "abi3", "plat2"),
tags.Tag("cp36", "abi3", "plat1"),
tags.Tag("cp36", "abi3", "plat2"),
tags.Tag("cp35", "abi3", "plat1"),
tags.Tag("cp35", "abi3", "plat2"),
tags.Tag("cp34", "abi3", "plat1"),
tags.Tag("cp34", "abi3", "plat2"),
tags.Tag("cp33", "abi3", "plat1"),
tags.Tag("cp33", "abi3", "plat2"),
tags.Tag("cp32", "abi3", "plat1"),
tags.Tag("cp32", "abi3", "plat2"),
]
result = list(tags.cpython_tags((3, 3), ["cp33m"], ["plat1", "plat2"]))
assert result == [
tags.Tag("cp33", "cp33m", "plat1"),
tags.Tag("cp33", "cp33m", "plat2"),
tags.Tag("cp33", "abi3", "plat1"),
tags.Tag("cp33", "abi3", "plat2"),
tags.Tag("cp33", "none", "plat1"),
tags.Tag("cp33", "none", "plat2"),
tags.Tag("cp32", "abi3", "plat1"),
tags.Tag("cp32", "abi3", "plat2"),
]
result = list(tags.cpython_tags((3, 13), ["cp313t"], ["plat1", "plat2"]))
assert result == [
tags.Tag("cp313", "cp313t", "plat1"),
tags.Tag("cp313", "cp313t", "plat2"),
tags.Tag("cp313", "none", "plat1"),
tags.Tag("cp313", "none", "plat2"),
]
def test_python_version_defaults(self) -> None:
tag = next(tags.cpython_tags(abis=["abi3"], platforms=["any"]))
interpreter = "cp" + tags._version_nodot(sys.version_info[:2])
assert interpreter == tag.interpreter
def test_abi_defaults(self, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(tags, "_cpython_abis", lambda _1, _2: ["cp38"])
result = list(tags.cpython_tags((3, 8), platforms=["any"]))
assert tags.Tag("cp38", "cp38", "any") in result
assert tags.Tag("cp38", "abi3", "any") in result
assert tags.Tag("cp38", "none", "any") in result
def test_abi_defaults_needs_underscore(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr(tags, "_cpython_abis", lambda _1, _2: ["cp311"])
result = list(tags.cpython_tags((3, 11), platforms=["any"]))
assert tags.Tag("cp311", "cp311", "any") in result
assert tags.Tag("cp311", "abi3", "any") in result
assert tags.Tag("cp311", "none", "any") in result
def test_platforms_defaults(self, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(tags, "platform_tags", lambda: ["plat1"])
result = list(tags.cpython_tags((3, 8), abis=["whatever"]))
assert tags.Tag("cp38", "whatever", "plat1") in result
def test_platforms_defaults_needs_underscore(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr(tags, "platform_tags", lambda: ["plat1"])
result = list(tags.cpython_tags((3, 11), abis=["whatever"]))
assert tags.Tag("cp311", "whatever", "plat1") in result
def test_platform_name_space_normalization(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
"""Ensure that spaces are translated to underscores in platform names."""
monkeypatch.setattr(sysconfig, "get_platform", lambda: "isilon onefs")
for tag in tags.cpython_tags():
assert " " not in tag.platform
def test_major_only_python_version(self) -> None:
result = list(tags.cpython_tags((3,), ["abi"], ["plat"]))
assert result == [
tags.Tag("cp3", "abi", "plat"),
tags.Tag("cp3", "none", "plat"),
]
def test_major_only_python_version_with_default_abis(self) -> None:
result = list(tags.cpython_tags((3,), platforms=["plat"]))
assert result == [tags.Tag("cp3", "none", "plat")]
@pytest.mark.parametrize("abis", [[], ["abi3"], ["none"]])
def test_skip_redundant_abis(self, abis: list[str]) -> None:
results = list(tags.cpython_tags((3, 0), abis=abis, platforms=["any"]))
assert results == [tags.Tag("cp30", "none", "any")]
def test_abi3_python33(self) -> None:
results = list(tags.cpython_tags((3, 3), abis=["cp33"], platforms=["plat"]))
assert results == [
tags.Tag("cp33", "cp33", "plat"),
tags.Tag("cp33", "abi3", "plat"),
tags.Tag("cp33", "none", "plat"),
tags.Tag("cp32", "abi3", "plat"),
]
def test_no_excess_abi3_python32(self) -> None:
results = list(tags.cpython_tags((3, 2), abis=["cp32"], platforms=["plat"]))
assert results == [
tags.Tag("cp32", "cp32", "plat"),
tags.Tag("cp32", "abi3", "plat"),
tags.Tag("cp32", "none", "plat"),
]
def test_no_abi3_python31(self) -> None:
results = list(tags.cpython_tags((3, 1), abis=["cp31"], platforms=["plat"]))
assert results == [
tags.Tag("cp31", "cp31", "plat"),
tags.Tag("cp31", "none", "plat"),
]
def test_no_abi3_python27(self) -> None:
results = list(tags.cpython_tags((2, 7), abis=["cp27"], platforms=["plat"]))
assert results == [
tags.Tag("cp27", "cp27", "plat"),
tags.Tag("cp27", "none", "plat"),
]
class TestGenericTags:
def test__generic_abi_macos(self, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(
sysconfig, "get_config_var", lambda _: ".cpython-37m-darwin.so"
)
monkeypatch.setattr(tags, "interpreter_name", lambda: "cp")
assert tags._generic_abi() == ["cp37m"]
def test__generic_abi_linux_cpython(self, monkeypatch: pytest.MonkeyPatch) -> None:
config = {
"Py_DEBUG": False,
"WITH_PYMALLOC": True,
"EXT_SUFFIX": ".cpython-37m-x86_64-linux-gnu.so",
}
monkeypatch.setattr(sysconfig, "get_config_var", config.__getitem__)
monkeypatch.setattr(tags, "interpreter_name", lambda: "cp")
# They are identical
assert tags._cpython_abis((3, 7)) == ["cp37m"]
assert tags._generic_abi() == ["cp37m"]
def test__generic_abi_jp(self, monkeypatch: pytest.MonkeyPatch) -> None:
config = {"EXT_SUFFIX": ".return_exactly_this.so"}
monkeypatch.setattr(sysconfig, "get_config_var", config.__getitem__)
assert tags._generic_abi() == ["return_exactly_this"]
def test__generic_abi_graal(self, monkeypatch: pytest.MonkeyPatch) -> None:
config = {"EXT_SUFFIX": ".graalpy-38-native-x86_64-darwin.so"}
monkeypatch.setattr(sysconfig, "get_config_var", config.__getitem__)
assert tags._generic_abi() == ["graalpy_38_native"]
def test__generic_abi_disable_gil(self, monkeypatch: pytest.MonkeyPatch) -> None:
config = {
"Py_DEBUG": False,
"EXT_SUFFIX": ".cpython-313t-x86_64-linux-gnu.so",
"WITH_PYMALLOC": 0,
"Py_GIL_DISABLED": 1,
}
monkeypatch.setattr(sysconfig, "get_config_var", config.__getitem__)
assert tags._generic_abi() == ["cp313t"]
assert tags._generic_abi() == tags._cpython_abis((3, 13))
def test__generic_abi_none(self, monkeypatch: pytest.MonkeyPatch) -> None:
config = {"EXT_SUFFIX": "..so"}
monkeypatch.setattr(sysconfig, "get_config_var", config.__getitem__)
assert tags._generic_abi() == []
@pytest.mark.parametrize("ext_suffix", ["invalid", None])
def test__generic_abi_error(
self, ext_suffix: str | None, monkeypatch: pytest.MonkeyPatch
) -> None:
config = {"EXT_SUFFIX": ext_suffix}
monkeypatch.setattr(sysconfig, "get_config_var", config.__getitem__)
with pytest.raises(SystemError) as e:
tags._generic_abi()
assert "EXT_SUFFIX" in str(e.value)
def test__generic_abi_linux_pypy(self, monkeypatch: pytest.MonkeyPatch) -> None:
# issue gh-606
config = {
"Py_DEBUG": False,
"EXT_SUFFIX": ".pypy39-pp73-x86_64-linux-gnu.so",
}
monkeypatch.setattr(sysconfig, "get_config_var", config.__getitem__)
monkeypatch.setattr(tags, "interpreter_name", lambda: "pp")
assert tags._generic_abi() == ["pypy39_pp73"]
def test__generic_abi_old_windows(self, monkeypatch: pytest.MonkeyPatch) -> None:
config = {
"EXT_SUFFIX": ".pyd",
"Py_DEBUG": 0,
"WITH_PYMALLOC": 0,
"Py_GIL_DISABLED": 0,
}
monkeypatch.setattr(sysconfig, "get_config_var", config.__getitem__)
assert tags._generic_abi() == tags._cpython_abis(sys.version_info[:2])
def test__generic_abi_windows(self, monkeypatch: pytest.MonkeyPatch) -> None:
config = {
"EXT_SUFFIX": ".cp310-win_amd64.pyd",
}
monkeypatch.setattr(sysconfig, "get_config_var", config.__getitem__)
assert tags._generic_abi() == ["cp310"]
@pytest.mark.skipif(sys.implementation.name != "cpython", reason="CPython-only")
def test__generic_abi_agree(self) -> None:
"""Test that the two methods of finding the abi tag agree"""
assert tags._generic_abi() == tags._cpython_abis(sys.version_info[:2])
def test_generic_platforms(self) -> None:
platform = sysconfig.get_platform().replace("-", "_")
platform = platform.replace(".", "_")
assert list(tags._generic_platforms()) == [platform]
def test_generic_platforms_space(self, monkeypatch: pytest.MonkeyPatch) -> None:
"""Ensure platform tags normalize spaces to underscores."""
platform_ = "isilon onefs"
monkeypatch.setattr(sysconfig, "get_platform", lambda: platform_)
assert list(tags._generic_platforms()) == [platform_.replace(" ", "_")]
def test_iterator_returned(self) -> None:
result_iterator = tags.generic_tags("sillywalk33", ["abi"], ["plat1", "plat2"])
assert isinstance(result_iterator, collections.abc.Iterator)
def test_all_args(self) -> None:
result_iterator = tags.generic_tags("sillywalk33", ["abi"], ["plat1", "plat2"])
result = list(result_iterator)
assert result == [
tags.Tag("sillywalk33", "abi", "plat1"),
tags.Tag("sillywalk33", "abi", "plat2"),
tags.Tag("sillywalk33", "none", "plat1"),
tags.Tag("sillywalk33", "none", "plat2"),
]
@pytest.mark.parametrize("abi", [[], ["none"]])
def test_abi_unspecified(self, abi: list[str]) -> None:
no_abi = list(tags.generic_tags("sillywalk34", abi, ["plat1", "plat2"]))
assert no_abi == [
tags.Tag("sillywalk34", "none", "plat1"),
tags.Tag("sillywalk34", "none", "plat2"),
]
def test_interpreter_default(self, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(tags, "interpreter_name", lambda: "sillywalk")
monkeypatch.setattr(tags, "interpreter_version", lambda warn: "NN") # noqa: ARG005
result = list(tags.generic_tags(abis=["none"], platforms=["any"]))
assert result == [tags.Tag("sillywalkNN", "none", "any")]
def test_abis_default(self, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(tags, "_generic_abi", lambda: ["abi"])
result = list(tags.generic_tags(interpreter="sillywalk", platforms=["any"]))
assert result == [
tags.Tag("sillywalk", "abi", "any"),
tags.Tag("sillywalk", "none", "any"),
]
def test_platforms_default(self, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(tags, "platform_tags", lambda: ["plat"])
result = list(tags.generic_tags(interpreter="sillywalk", abis=["none"]))
assert result == [tags.Tag("sillywalk", "none", "plat")]
class TestCompatibleTags:
def test_all_args(self) -> None:
result = list(tags.compatible_tags((3, 3), "cp33", ["plat1", "plat2"]))
assert result == [
tags.Tag("py33", "none", "plat1"),
tags.Tag("py33", "none", "plat2"),
tags.Tag("py3", "none", "plat1"),
tags.Tag("py3", "none", "plat2"),
tags.Tag("py32", "none", "plat1"),
tags.Tag("py32", "none", "plat2"),
tags.Tag("py31", "none", "plat1"),
tags.Tag("py31", "none", "plat2"),
tags.Tag("py30", "none", "plat1"),
tags.Tag("py30", "none", "plat2"),
tags.Tag("cp33", "none", "any"),
tags.Tag("py33", "none", "any"),
tags.Tag("py3", "none", "any"),
tags.Tag("py32", "none", "any"),
tags.Tag("py31", "none", "any"),
tags.Tag("py30", "none", "any"),
]
def test_all_args_needs_underscore(self) -> None:
result = list(tags.compatible_tags((3, 11), "cp311", ["plat1", "plat2"]))
assert result == [
tags.Tag("py311", "none", "plat1"),
tags.Tag("py311", "none", "plat2"),
tags.Tag("py3", "none", "plat1"),
tags.Tag("py3", "none", "plat2"),
tags.Tag("py310", "none", "plat1"),
tags.Tag("py310", "none", "plat2"),
tags.Tag("py39", "none", "plat1"),
tags.Tag("py39", "none", "plat2"),
tags.Tag("py38", "none", "plat1"),
tags.Tag("py38", "none", "plat2"),
tags.Tag("py37", "none", "plat1"),
tags.Tag("py37", "none", "plat2"),
tags.Tag("py36", "none", "plat1"),
tags.Tag("py36", "none", "plat2"),
tags.Tag("py35", "none", "plat1"),
tags.Tag("py35", "none", "plat2"),
tags.Tag("py34", "none", "plat1"),
tags.Tag("py34", "none", "plat2"),
tags.Tag("py33", "none", "plat1"),
tags.Tag("py33", "none", "plat2"),
tags.Tag("py32", "none", "plat1"),
tags.Tag("py32", "none", "plat2"),
tags.Tag("py31", "none", "plat1"),
tags.Tag("py31", "none", "plat2"),
tags.Tag("py30", "none", "plat1"),
tags.Tag("py30", "none", "plat2"),
tags.Tag("cp311", "none", "any"),
tags.Tag("py311", "none", "any"),
tags.Tag("py3", "none", "any"),
tags.Tag("py310", "none", "any"),
tags.Tag("py39", "none", "any"),
tags.Tag("py38", "none", "any"),
tags.Tag("py37", "none", "any"),
tags.Tag("py36", "none", "any"),
tags.Tag("py35", "none", "any"),
tags.Tag("py34", "none", "any"),
tags.Tag("py33", "none", "any"),
tags.Tag("py32", "none", "any"),
tags.Tag("py31", "none", "any"),
tags.Tag("py30", "none", "any"),
]
def test_major_only_python_version(self) -> None:
result = list(tags.compatible_tags((3,), "cp33", ["plat"]))
assert result == [
tags.Tag("py3", "none", "plat"),
tags.Tag("cp33", "none", "any"),
tags.Tag("py3", "none", "any"),
]
def test_default_python_version(self, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(sys, "version_info", (3, 1))
result = list(tags.compatible_tags(interpreter="cp31", platforms=["plat"]))
assert result == [
tags.Tag("py31", "none", "plat"),
tags.Tag("py3", "none", "plat"),
tags.Tag("py30", "none", "plat"),
tags.Tag("cp31", "none", "any"),
tags.Tag("py31", "none", "any"),
tags.Tag("py3", "none", "any"),
tags.Tag("py30", "none", "any"),
]
def test_default_python_version_needs_underscore(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr(sys, "version_info", (3, 11))
result = list(tags.compatible_tags(interpreter="cp311", platforms=["plat"]))
assert result == [
tags.Tag("py311", "none", "plat"),
tags.Tag("py3", "none", "plat"),
tags.Tag("py310", "none", "plat"),
tags.Tag("py39", "none", "plat"),
tags.Tag("py38", "none", "plat"),
tags.Tag("py37", "none", "plat"),
tags.Tag("py36", "none", "plat"),
tags.Tag("py35", "none", "plat"),
tags.Tag("py34", "none", "plat"),
tags.Tag("py33", "none", "plat"),
tags.Tag("py32", "none", "plat"),
tags.Tag("py31", "none", "plat"),
tags.Tag("py30", "none", "plat"),
tags.Tag("cp311", "none", "any"),
tags.Tag("py311", "none", "any"),
tags.Tag("py3", "none", "any"),
tags.Tag("py310", "none", "any"),
tags.Tag("py39", "none", "any"),
tags.Tag("py38", "none", "any"),
tags.Tag("py37", "none", "any"),
tags.Tag("py36", "none", "any"),
tags.Tag("py35", "none", "any"),
tags.Tag("py34", "none", "any"),
tags.Tag("py33", "none", "any"),
tags.Tag("py32", "none", "any"),
tags.Tag("py31", "none", "any"),
tags.Tag("py30", "none", "any"),
]
def test_default_interpreter(self) -> None:
result = list(tags.compatible_tags((3, 1), platforms=["plat"]))
assert result == [
tags.Tag("py31", "none", "plat"),
tags.Tag("py3", "none", "plat"),
tags.Tag("py30", "none", "plat"),
tags.Tag("py31", "none", "any"),
tags.Tag("py3", "none", "any"),
tags.Tag("py30", "none", "any"),
]
def test_default_platforms(self, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(tags, "platform_tags", lambda: iter(["plat", "plat2"]))
result = list(tags.compatible_tags((3, 1), "cp31"))
assert result == [
tags.Tag("py31", "none", "plat"),
tags.Tag("py31", "none", "plat2"),
tags.Tag("py3", "none", "plat"),
tags.Tag("py3", "none", "plat2"),
tags.Tag("py30", "none", "plat"),
tags.Tag("py30", "none", "plat2"),
tags.Tag("cp31", "none", "any"),
tags.Tag("py31", "none", "any"),
tags.Tag("py3", "none", "any"),
tags.Tag("py30", "none", "any"),
]
class TestSysTags:
def teardown_method(self) -> None:
# Clear the version cache
tags._glibc_version = [] # type: ignore[attr-defined]
@pytest.mark.parametrize(
("name", "expected"),
[("CPython", "cp"), ("PyPy", "pp"), ("Jython", "jy"), ("IronPython", "ip")],
)
def test_interpreter_name(
self, name: str, expected: str, mock_interpreter_name: Callable[[str], bool]
) -> None:
mock_interpreter_name(name)
assert tags.interpreter_name() == expected
def test_iterator(self) -> None:
assert isinstance(tags.sys_tags(), collections.abc.Iterator)
def test_mac_cpython(
self,
mock_interpreter_name: Callable[[str], bool],
monkeypatch: pytest.MonkeyPatch,
) -> None:
if mock_interpreter_name("CPython"):
monkeypatch.setattr(tags, "_cpython_abis", lambda *a: ["cp33m"])
if platform.system() != "Darwin":
monkeypatch.setattr(platform, "system", lambda: "Darwin")
monkeypatch.setattr(tags, "mac_platforms", lambda: ["macosx_10_5_x86_64"])
abis = tags._cpython_abis(sys.version_info[:2])
platforms = list(tags.mac_platforms())
result = list(tags.sys_tags())
assert len(abis) == 1
assert result[0] == tags.Tag(
"cp" + tags._version_nodot(sys.version_info[:2]), abis[0], platforms[0]
)
assert result[-1] == tags.Tag(
"py" + tags._version_nodot((sys.version_info[0], 0)), "none", "any"
)
def test_windows_cpython(
self,
mock_interpreter_name: Callable[[str], bool],
monkeypatch: pytest.MonkeyPatch,
) -> None:
if mock_interpreter_name("CPython"):
monkeypatch.setattr(tags, "_cpython_abis", lambda *a: ["cp33m"])
if platform.system() != "Windows":
monkeypatch.setattr(platform, "system", lambda: "Windows")
monkeypatch.setattr(tags, "_generic_platforms", lambda: ["win_amd64"])
abis = list(tags._cpython_abis(sys.version_info[:2]))
platforms = list(tags._generic_platforms())
result = list(tags.sys_tags())
interpreter = "cp" + tags._version_nodot(sys.version_info[:2])
assert len(abis) == 1
expected = tags.Tag(interpreter, abis[0], platforms[0])
assert result[0] == expected
expected = tags.Tag(
"py" + tags._version_nodot((sys.version_info[0], 0)), "none", "any"
)
assert result[-1] == expected
def test_linux_cpython(
self,
mock_interpreter_name: Callable[[str], bool],
monkeypatch: pytest.MonkeyPatch,
) -> None:
if mock_interpreter_name("CPython"):
monkeypatch.setattr(tags, "_cpython_abis", lambda *a: ["cp33m"])
if platform.system() != "Linux":
monkeypatch.setattr(platform, "system", lambda: "Linux")
monkeypatch.setattr(tags, "_linux_platforms", lambda: ["linux_x86_64"])
abis = list(tags._cpython_abis(sys.version_info[:2]))
platforms = list(tags._linux_platforms())
result = list(tags.sys_tags())
expected_interpreter = "cp" + tags._version_nodot(sys.version_info[:2])
assert len(abis) == 1
assert result[0] == tags.Tag(expected_interpreter, abis[0], platforms[0])
expected = tags.Tag(
"py" + tags._version_nodot((sys.version_info[0], 0)), "none", "any"
)
assert result[-1] == expected
def test_generic(self, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(platform, "system", lambda: "Generic")
monkeypatch.setattr(tags, "interpreter_name", lambda: "generic")
result = list(tags.sys_tags())
expected = tags.Tag(
"py" + tags._version_nodot((sys.version_info[0], 0)), "none", "any"
)
assert result[-1] == expected
@pytest.mark.usefixtures("manylinux_module")
def test_linux_platforms_manylinux2014_armv6l(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr(sysconfig, "get_platform", lambda: "linux_armv6l")
monkeypatch.setattr(os, "confstr", lambda _: "glibc 2.20", raising=False)
platforms = list(tags._linux_platforms(is_32bit=True))
expected = ["linux_armv6l"]
assert platforms == expected
def test_skip_manylinux_2014(
self, monkeypatch: pytest.MonkeyPatch, manylinux_module: types.ModuleType
) -> None:
monkeypatch.setattr(sysconfig, "get_platform", lambda: "linux_ppc64")
monkeypatch.setattr(tags._manylinux, "_get_glibc_version", lambda: (2, 20)) # type: ignore[attr-defined]
monkeypatch.setattr(
manylinux_module, "manylinux2014_compatible", False, raising=False
)
expected = [
"manylinux_2_20_ppc64",
"manylinux_2_19_ppc64",
"manylinux_2_18_ppc64",
# "manylinux2014_ppc64", # this one is skipped
# "manylinux_2_17_ppc64", # this one is also skipped
"linux_ppc64",
]
platforms = list(tags._linux_platforms())
assert platforms == expected
@pytest.mark.usefixtures("manylinux_module")
@pytest.mark.parametrize(
("machine", "abi", "alt_machine"),
[("x86_64", "x32", "i686"), ("armv7l", "armel", "armv7l")],
)
def test_linux_platforms_not_manylinux_abi(
self, monkeypatch: pytest.MonkeyPatch, machine: str, abi: str, alt_machine: str
) -> None:
monkeypatch.setattr(sysconfig, "get_platform", lambda: f"linux_{machine}")
monkeypatch.setattr(
sys,
"executable",
os.path.join(
os.path.dirname(__file__),
"manylinux",
f"hello-world-{machine}-{abi}",
),
)
platforms = list(tags._linux_platforms(is_32bit=True))
expected = [f"linux_{alt_machine}"]
assert platforms == expected
@pytest.mark.parametrize(
("machine", "major", "minor", "tf"),
[("x86_64", 2, 20, False), ("s390x", 2, 22, True)],
)
def test_linux_use_manylinux_compatible(
self,
monkeypatch: pytest.MonkeyPatch,
manylinux_module: types.ModuleType,
machine: str,
major: int,
minor: int,
tf: bool,
) -> None:
def manylinux_compatible(tag_major: int, tag_minor: int, tag_arch: str) -> bool:
if tag_major == 2 and tag_minor == 22:
return tag_arch == "s390x"
return False
monkeypatch.setattr(
tags._manylinux, # type: ignore[attr-defined]
"_get_glibc_version",
lambda: (major, minor),
)
monkeypatch.setattr(sysconfig, "get_platform", lambda: f"linux_{machine}")
monkeypatch.setattr(
manylinux_module,
"manylinux_compatible",
manylinux_compatible,
raising=False,
)
platforms = list(tags._linux_platforms(is_32bit=False))
expected = [f"manylinux_2_22_{machine}"] if tf else []
expected.append(f"linux_{machine}")
assert platforms == expected
def test_linux_use_manylinux_compatible_none(
self, monkeypatch: pytest.MonkeyPatch, manylinux_module: types.ModuleType
) -> None:
def manylinux_compatible(
tag_major: int,
tag_minor: int,
tag_arch: str, # noqa: ARG001
) -> bool | None:
if tag_major == 2 and tag_minor < 25:
return False
return None
monkeypatch.setattr(tags._manylinux, "_get_glibc_version", lambda: (2, 30)) # type: ignore[attr-defined]
monkeypatch.setattr(sysconfig, "get_platform", lambda: "linux_x86_64")
monkeypatch.setattr(
manylinux_module,
"manylinux_compatible",
manylinux_compatible,
raising=False,
)
platforms = list(tags._linux_platforms(is_32bit=False))
expected = [
"manylinux_2_30_x86_64",
"manylinux_2_29_x86_64",
"manylinux_2_28_x86_64",
"manylinux_2_27_x86_64",
"manylinux_2_26_x86_64",
"manylinux_2_25_x86_64",
"linux_x86_64",
]
assert platforms == expected
def test_pypy_first_none_any_tag(self, monkeypatch: pytest.MonkeyPatch) -> None:
# When building the complete list of pypy tags, make sure the first
# -none-any one is pp3-none-any
monkeypatch.setattr(tags, "interpreter_name", lambda: "pp")
for tag in tags.sys_tags():
if tag.abi == "none" and tag.platform == "any":
break
assert tag == tags.Tag("pp3", "none", "any")
def test_cpython_first_none_any_tag(self, monkeypatch: pytest.MonkeyPatch) -> None:
# When building the complete list of cpython tags, make sure the first
# -none-any one is cpxx-none-any
monkeypatch.setattr(tags, "interpreter_name", lambda: "cp")
# Find the first tag that is ABI- and platform-agnostic.
for tag in tags.sys_tags():
if tag.abi == "none" and tag.platform == "any":
break
interpreter = f"cp{tags.interpreter_version()}"
assert tag == tags.Tag(interpreter, "none", "any")
class TestBitness:
def teardown_method(self) -> None:
importlib.reload(tags)
@pytest.mark.parametrize(
("maxsize", "sizeof_voidp", "expected"),
[
# 64-bit
(9223372036854775807, 8, False),
# 32-bit
(2147483647, 4, True),
# 64-bit w/ 32-bit sys.maxsize: GraalPy, IronPython, Jython
(2147483647, 8, False),
],
)
def test_32bit_interpreter(
self,
maxsize: int,
sizeof_voidp: int,
expected: bool,
monkeypatch: pytest.MonkeyPatch,
) -> None:
def _calcsize(fmt: str) -> int:
assert fmt == "P"
return sizeof_voidp
monkeypatch.setattr(sys, "maxsize", maxsize)
monkeypatch.setattr(struct, "calcsize", _calcsize)
importlib.reload(tags)
assert expected == tags._32_BIT_INTERPRETER
def test_pickle() -> None:
# Make sure equality works between a pickle/unpickle round trip.
tag = tags.Tag("py3", "none", "any")
assert pickle.loads(pickle.dumps(tag)) == tag
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1768936045.8203685
packaging-26.0/tests/test_utils.py 0000644 0000000 0000000 00000012754 15133751156 014246 0 ustar 00 # This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import annotations
import pytest
from packaging.tags import Tag
from packaging.utils import (
InvalidName,
InvalidSdistFilename,
InvalidWheelFilename,
canonicalize_name,
canonicalize_version,
is_normalized_name,
parse_sdist_filename,
parse_wheel_filename,
)
from packaging.version import Version
@pytest.mark.parametrize(
("name", "expected"),
[
("foo", "foo"),
("Foo", "foo"),
("fOo", "foo"),
("foo.bar", "foo-bar"),
("Foo.Bar", "foo-bar"),
("Foo.....Bar", "foo-bar"),
("foo_bar", "foo-bar"),
("foo___bar", "foo-bar"),
("foo-bar", "foo-bar"),
("foo----bar", "foo-bar"),
],
)
def test_canonicalize_name(name: str, expected: str) -> None:
assert canonicalize_name(name) == expected
@pytest.mark.parametrize(
("name", "expected"),
[
("_not_legal", "-not-legal"),
("hi\n", "hi\n"),
("\nhi", "\nhi"),
("h\ni", "h\ni"),
("hi\r", "hi\r"),
("\rhi", "\rhi"),
("h\ri", "h\ri"),
],
)
def test_canonicalize_name_invalid(name: str, expected: str) -> None:
with pytest.raises(InvalidName):
canonicalize_name(name, validate=True)
assert canonicalize_name(name) == expected
@pytest.mark.parametrize(
("name", "expected"),
[
("foo", "foo"),
("Foo", "foo"),
("fOo", "foo"),
("foo.bar", "foo-bar"),
("Foo.Bar", "foo-bar"),
("Foo.....Bar", "foo-bar"),
("foo_bar", "foo-bar"),
("foo___bar", "foo-bar"),
("foo-bar", "foo-bar"),
("foo----bar", "foo-bar"),
],
)
def test_is_normalized_name(name: str, expected: str) -> None:
assert is_normalized_name(expected)
if name != expected:
assert not is_normalized_name(name)
@pytest.mark.parametrize(
("version", "expected"),
[
(Version("1.4.0"), "1.4"),
("1.4.0", "1.4"),
("1.40.0", "1.40"),
("1.4.0.0.00.000.0000", "1.4"),
("1.0", "1"),
("1.0+abc", "1+abc"),
("1.0.dev0", "1.dev0"),
("1.0.post0", "1.post0"),
("1.0a0", "1a0"),
("1.0rc0", "1rc0"),
("100!0.0", "100!0"),
# improper version strings are unchanged
("lolwat", "lolwat"),
("1.0.1-test7", "1.0.1-test7"),
],
)
def test_canonicalize_version(version: str, expected: str) -> None:
assert canonicalize_version(version) == expected
@pytest.mark.parametrize(("version"), ["1.4.0", "1.0"])
def test_canonicalize_version_no_strip_trailing_zero(version: str) -> None:
assert canonicalize_version(version, strip_trailing_zero=False) == version
@pytest.mark.parametrize(
("filename", "name", "version", "build", "tags"),
[
(
"foo-1.0-py3-none-any.whl",
"foo",
Version("1.0"),
(),
{Tag("py3", "none", "any")},
),
(
"some_PACKAGE-1.0-py3-none-any.whl",
"some-package",
Version("1.0"),
(),
{Tag("py3", "none", "any")},
),
(
"foo-1.0-1000-py3-none-any.whl",
"foo",
Version("1.0"),
(1000, ""),
{Tag("py3", "none", "any")},
),
(
"foo-1.0-1000abc-py3-none-any.whl",
"foo",
Version("1.0"),
(1000, "abc"),
{Tag("py3", "none", "any")},
),
(
"foo_bár-1.0-py3-none-any.whl",
"foo-bár",
Version("1.0"),
(),
{Tag("py3", "none", "any")},
),
(
"foo_bár-1.0-1000-py3-none-any.whl",
"foo-bár",
Version("1.0"),
(1000, ""),
{Tag("py3", "none", "any")},
),
],
)
def test_parse_wheel_filename(
filename: str, name: str, version: Version, build: tuple[int, str], tags: set[Tag]
) -> None:
assert parse_wheel_filename(filename) == (name, version, build, frozenset(tags))
@pytest.mark.parametrize(
("filename"),
[
("foo-1.0.whl"), # Missing tags
("foo-1.0-py3-none-any.wheel"), # Incorrect file extension (`.wheel`)
("foo__bar-1.0-py3-none-any.whl"), # Invalid name (`__`)
("foo#bar-1.0-py3-none-any.whl"), # Invalid name (`#`)
("foobar-1.x-py3-none-any.whl"), # Invalid version (`1.x`)
# Build number doesn't start with a digit (`abc`)
("foo-1.0-abc-py3-none-any.whl"),
("foo-1.0-200-py3-none-any-junk.whl"), # Too many dashes (`-junk`)
],
)
def test_parse_wheel_invalid_filename(filename: str) -> None:
with pytest.raises(InvalidWheelFilename):
parse_wheel_filename(filename)
@pytest.mark.parametrize(
("filename", "name", "version"),
[("foo-1.0.tar.gz", "foo", Version("1.0")), ("foo-1.0.zip", "foo", Version("1.0"))],
)
def test_parse_sdist_filename(filename: str, name: str, version: Version) -> None:
assert parse_sdist_filename(filename) == (name, version)
@pytest.mark.parametrize(
("filename"),
[
("foo-1.0.xz"), # Incorrect extension
("foo1.0.tar.gz"), # Missing separator
("foo-1.x.tar.gz"), # Invalid version
],
)
def test_parse_sdist_invalid_filename(filename: str) -> None:
with pytest.raises(InvalidSdistFilename):
parse_sdist_filename(filename)
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1768936045.8203685
packaging-26.0/tests/test_version.py 0000644 0000000 0000000 00000107400 15133751156 014564 0 ustar 00 # This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import annotations
import itertools
import operator
import sys
import typing
import pretend
import pytest
from packaging.version import InvalidVersion, Version, _VersionReplace, parse
if typing.TYPE_CHECKING:
from collections.abc import Callable
from typing_extensions import Self, Unpack
if sys.version_info >= (3, 13):
from copy import replace
else:
T = typing.TypeVar("T")
class SupportsReplace(typing.Protocol):
def __replace__(self, **kwargs: Unpack[_VersionReplace]) -> Self: ...
S = typing.TypeVar("S", bound="SupportsReplace")
def replace(item: S, **kwargs: Unpack[_VersionReplace]) -> S:
return item.__replace__(**kwargs)
def test_parse() -> None:
assert isinstance(parse("1.0"), Version)
def test_parse_raises() -> None:
with pytest.raises(InvalidVersion):
parse("lolwat")
# This list must be in the correct sorting order
VERSIONS = [
# Implicit epoch of 0
"1.0.dev456",
"1.0a1",
"1.0a2.dev456",
"1.0a12.dev456",
"1.0a12",
"1.0b1.dev456",
"1.0b2",
"1.0b2.post345.dev456",
"1.0b2.post345",
"1.0b2-346",
"1.0c1.dev456",
"1.0c1",
"1.0rc2",
"1.0c3",
"1.0",
"1.0.post456.dev34",
"1.0.post456",
"1.1.dev1",
"1.2+123abc",
"1.2+123abc456",
"1.2+abc",
"1.2+abc123",
"1.2+abc123def",
"1.2+1234.abc",
"1.2+123456",
"1.2.r32+123456",
"1.2.rev33+123456",
# Explicit epoch of 1
"1!1.0.dev456",
"1!1.0a1",
"1!1.0a2.dev456",
"1!1.0a12.dev456",
"1!1.0a12",
"1!1.0b1.dev456",
"1!1.0b2",
"1!1.0b2.post345.dev456",
"1!1.0b2.post345",
"1!1.0b2-346",
"1!1.0c1.dev456",
"1!1.0c1",
"1!1.0rc2",
"1!1.0c3",
"1!1.0",
"1!1.0.post456.dev34",
"1!1.0.post456",
"1!1.1.dev1",
"1!1.2+123abc",
"1!1.2+123abc456",
"1!1.2+abc",
"1!1.2+abc123",
"1!1.2+abc123def",
"1!1.2+1234.abc",
"1!1.2+123456",
"1!1.2.r32+123456",
"1!1.2.rev33+123456",
]
class TestVersion:
@pytest.mark.parametrize("version", VERSIONS)
def test_valid_versions(self, version: str) -> None:
Version(version)
def test_match_args(self) -> None:
assert Version.__match_args__ == ("_str",)
assert Version("1.2")._str == "1.2"
@pytest.mark.parametrize(
"version",
[
# Non sensical versions should be invalid
"french toast",
# Versions with invalid local versions
"1.0+a+",
"1.0++",
"1.0+_foobar",
"1.0+foo&asd",
"1.0+1+1",
],
)
def test_invalid_versions(self, version: str) -> None:
with pytest.raises(InvalidVersion):
Version(version)
@pytest.mark.parametrize(
("version", "normalized"),
[
# Various development release incarnations
("1.0dev", "1.0.dev0"),
("1.0.dev", "1.0.dev0"),
("1.0dev1", "1.0.dev1"),
("1.0-dev", "1.0.dev0"),
("1.0-dev1", "1.0.dev1"),
("1.0DEV", "1.0.dev0"),
("1.0.DEV", "1.0.dev0"),
("1.0DEV1", "1.0.dev1"),
("1.0.DEV1", "1.0.dev1"),
("1.0-DEV", "1.0.dev0"),
("1.0-DEV1", "1.0.dev1"),
# Various alpha incarnations
("1.0a", "1.0a0"),
("1.0.a", "1.0a0"),
("1.0.a1", "1.0a1"),
("1.0-a", "1.0a0"),
("1.0-a1", "1.0a1"),
("1.0alpha", "1.0a0"),
("1.0.alpha", "1.0a0"),
("1.0.alpha1", "1.0a1"),
("1.0-alpha", "1.0a0"),
("1.0-alpha1", "1.0a1"),
("1.0A", "1.0a0"),
("1.0.A", "1.0a0"),
("1.0.A1", "1.0a1"),
("1.0-A", "1.0a0"),
("1.0-A1", "1.0a1"),
("1.0ALPHA", "1.0a0"),
("1.0.ALPHA", "1.0a0"),
("1.0.ALPHA1", "1.0a1"),
("1.0-ALPHA", "1.0a0"),
("1.0-ALPHA1", "1.0a1"),
# Various beta incarnations
("1.0b", "1.0b0"),
("1.0.b", "1.0b0"),
("1.0.b1", "1.0b1"),
("1.0-b", "1.0b0"),
("1.0-b1", "1.0b1"),
("1.0beta", "1.0b0"),
("1.0.beta", "1.0b0"),
("1.0.beta1", "1.0b1"),
("1.0-beta", "1.0b0"),
("1.0-beta1", "1.0b1"),
("1.0B", "1.0b0"),
("1.0.B", "1.0b0"),
("1.0.B1", "1.0b1"),
("1.0-B", "1.0b0"),
("1.0-B1", "1.0b1"),
("1.0BETA", "1.0b0"),
("1.0.BETA", "1.0b0"),
("1.0.BETA1", "1.0b1"),
("1.0-BETA", "1.0b0"),
("1.0-BETA1", "1.0b1"),
# Various release candidate incarnations
("1.0c", "1.0rc0"),
("1.0.c", "1.0rc0"),
("1.0.c1", "1.0rc1"),
("1.0-c", "1.0rc0"),
("1.0-c1", "1.0rc1"),
("1.0rc", "1.0rc0"),
("1.0.rc", "1.0rc0"),
("1.0.rc1", "1.0rc1"),
("1.0-rc", "1.0rc0"),
("1.0-rc1", "1.0rc1"),
("1.0C", "1.0rc0"),
("1.0.C", "1.0rc0"),
("1.0.C1", "1.0rc1"),
("1.0-C", "1.0rc0"),
("1.0-C1", "1.0rc1"),
("1.0RC", "1.0rc0"),
("1.0.RC", "1.0rc0"),
("1.0.RC1", "1.0rc1"),
("1.0-RC", "1.0rc0"),
("1.0-RC1", "1.0rc1"),
# Various post release incarnations
("1.0post", "1.0.post0"),
("1.0.post", "1.0.post0"),
("1.0post1", "1.0.post1"),
("1.0-post", "1.0.post0"),
("1.0-post1", "1.0.post1"),
("1.0POST", "1.0.post0"),
("1.0.POST", "1.0.post0"),
("1.0POST1", "1.0.post1"),
("1.0r", "1.0.post0"),
("1.0rev", "1.0.post0"),
("1.0.POST1", "1.0.post1"),
("1.0.r1", "1.0.post1"),
("1.0.rev1", "1.0.post1"),
("1.0-POST", "1.0.post0"),
("1.0-POST1", "1.0.post1"),
("1.0-5", "1.0.post5"),
("1.0-r5", "1.0.post5"),
("1.0-rev5", "1.0.post5"),
# Local version case insensitivity
("1.0+AbC", "1.0+abc"),
# Integer Normalization
("1.01", "1.1"),
("1.0a05", "1.0a5"),
("1.0b07", "1.0b7"),
("1.0c056", "1.0rc56"),
("1.0rc09", "1.0rc9"),
("1.0.post000", "1.0.post0"),
("1.1.dev09000", "1.1.dev9000"),
("00!1.2", "1.2"),
("0100!0.0", "100!0.0"),
# Various other normalizations
("v1.0", "1.0"),
(" v1.0\t\n", "1.0"),
],
)
def test_normalized_versions(self, version: str, normalized: str) -> None:
assert str(Version(version)) == normalized
@pytest.mark.parametrize(
("version", "expected"),
[
("1.0.dev456", "1.0.dev456"),
("1.0a1", "1.0a1"),
("1.0a2.dev456", "1.0a2.dev456"),
("1.0a12.dev456", "1.0a12.dev456"),
("1.0a12", "1.0a12"),
("1.0b1.dev456", "1.0b1.dev456"),
("1.0b2", "1.0b2"),
("1.0b2.post345.dev456", "1.0b2.post345.dev456"),
("1.0b2.post345", "1.0b2.post345"),
("1.0rc1.dev456", "1.0rc1.dev456"),
("1.0rc1", "1.0rc1"),
("1.0", "1.0"),
("1.0.post456.dev34", "1.0.post456.dev34"),
("1.0.post456", "1.0.post456"),
("1.0.1", "1.0.1"),
("0!1.0.2", "1.0.2"),
("1.0.3+7", "1.0.3+7"),
("0!1.0.4+8.0", "1.0.4+8.0"),
("1.0.5+9.5", "1.0.5+9.5"),
("1.2+1234.abc", "1.2+1234.abc"),
("1.2+123456", "1.2+123456"),
("1.2+123abc", "1.2+123abc"),
("1.2+123abc456", "1.2+123abc456"),
("1.2+abc", "1.2+abc"),
("1.2+abc123", "1.2+abc123"),
("1.2+abc123def", "1.2+abc123def"),
("1.1.dev1", "1.1.dev1"),
("7!1.0.dev456", "7!1.0.dev456"),
("7!1.0a1", "7!1.0a1"),
("7!1.0a2.dev456", "7!1.0a2.dev456"),
("7!1.0a12.dev456", "7!1.0a12.dev456"),
("7!1.0a12", "7!1.0a12"),
("7!1.0b1.dev456", "7!1.0b1.dev456"),
("7!1.0b2", "7!1.0b2"),
("7!1.0b2.post345.dev456", "7!1.0b2.post345.dev456"),
("7!1.0b2.post345", "7!1.0b2.post345"),
("7!1.0rc1.dev456", "7!1.0rc1.dev456"),
("7!1.0rc1", "7!1.0rc1"),
("7!1.0", "7!1.0"),
("7!1.0.post456.dev34", "7!1.0.post456.dev34"),
("7!1.0.post456", "7!1.0.post456"),
("7!1.0.1", "7!1.0.1"),
("7!1.0.2", "7!1.0.2"),
("7!1.0.3+7", "7!1.0.3+7"),
("7!1.0.4+8.0", "7!1.0.4+8.0"),
("7!1.0.5+9.5", "7!1.0.5+9.5"),
("7!1.1.dev1", "7!1.1.dev1"),
],
)
def test_version_str_repr(self, version: str, expected: str) -> None:
assert str(Version(version)) == expected
assert repr(Version(version)) == f""
def test_version_rc_and_c_equals(self) -> None:
assert Version("1.0rc1") == Version("1.0c1")
@pytest.mark.parametrize("version", VERSIONS)
def test_version_hash(self, version: str) -> None:
assert hash(Version(version)) == hash(Version(version))
@pytest.mark.parametrize(
("version", "public"),
[
("1.0", "1.0"),
("1.0.dev0", "1.0.dev0"),
("1.0.dev6", "1.0.dev6"),
("1.0a1", "1.0a1"),
("1.0a1.post5", "1.0a1.post5"),
("1.0a1.post5.dev6", "1.0a1.post5.dev6"),
("1.0rc4", "1.0rc4"),
("1.0.post5", "1.0.post5"),
("1!1.0", "1!1.0"),
("1!1.0.dev6", "1!1.0.dev6"),
("1!1.0a1", "1!1.0a1"),
("1!1.0a1.post5", "1!1.0a1.post5"),
("1!1.0a1.post5.dev6", "1!1.0a1.post5.dev6"),
("1!1.0rc4", "1!1.0rc4"),
("1!1.0.post5", "1!1.0.post5"),
("1.0+deadbeef", "1.0"),
("1.0.dev6+deadbeef", "1.0.dev6"),
("1.0a1+deadbeef", "1.0a1"),
("1.0a1.post5+deadbeef", "1.0a1.post5"),
("1.0a1.post5.dev6+deadbeef", "1.0a1.post5.dev6"),
("1.0rc4+deadbeef", "1.0rc4"),
("1.0.post5+deadbeef", "1.0.post5"),
("1!1.0+deadbeef", "1!1.0"),
("1!1.0.dev6+deadbeef", "1!1.0.dev6"),
("1!1.0a1+deadbeef", "1!1.0a1"),
("1!1.0a1.post5+deadbeef", "1!1.0a1.post5"),
("1!1.0a1.post5.dev6+deadbeef", "1!1.0a1.post5.dev6"),
("1!1.0rc4+deadbeef", "1!1.0rc4"),
("1!1.0.post5+deadbeef", "1!1.0.post5"),
],
)
def test_version_public(self, version: str, public: str) -> None:
assert Version(version).public == public
@pytest.mark.parametrize(
("version", "base_version"),
[
("1.0", "1.0"),
("1.0.dev0", "1.0"),
("1.0.dev6", "1.0"),
("1.0a1", "1.0"),
("1.0a1.post5", "1.0"),
("1.0a1.post5.dev6", "1.0"),
("1.0rc4", "1.0"),
("1.0.post5", "1.0"),
("1!1.0", "1!1.0"),
("1!1.0.dev6", "1!1.0"),
("1!1.0a1", "1!1.0"),
("1!1.0a1.post5", "1!1.0"),
("1!1.0a1.post5.dev6", "1!1.0"),
("1!1.0rc4", "1!1.0"),
("1!1.0.post5", "1!1.0"),
("1.0+deadbeef", "1.0"),
("1.0.dev6+deadbeef", "1.0"),
("1.0a1+deadbeef", "1.0"),
("1.0a1.post5+deadbeef", "1.0"),
("1.0a1.post5.dev6+deadbeef", "1.0"),
("1.0rc4+deadbeef", "1.0"),
("1.0.post5+deadbeef", "1.0"),
("1!1.0+deadbeef", "1!1.0"),
("1!1.0.dev6+deadbeef", "1!1.0"),
("1!1.0a1+deadbeef", "1!1.0"),
("1!1.0a1.post5+deadbeef", "1!1.0"),
("1!1.0a1.post5.dev6+deadbeef", "1!1.0"),
("1!1.0rc4+deadbeef", "1!1.0"),
("1!1.0.post5+deadbeef", "1!1.0"),
],
)
def test_version_base_version(self, version: str, base_version: str) -> None:
assert Version(version).base_version == base_version
@pytest.mark.parametrize(
("version", "epoch"),
[
("1.0", 0),
("1.0.dev0", 0),
("1.0.dev6", 0),
("1.0a1", 0),
("1.0a1.post5", 0),
("1.0a1.post5.dev6", 0),
("1.0rc4", 0),
("1.0.post5", 0),
("1!1.0", 1),
("1!1.0.dev6", 1),
("1!1.0a1", 1),
("1!1.0a1.post5", 1),
("1!1.0a1.post5.dev6", 1),
("1!1.0rc4", 1),
("1!1.0.post5", 1),
("1.0+deadbeef", 0),
("1.0.dev6+deadbeef", 0),
("1.0a1+deadbeef", 0),
("1.0a1.post5+deadbeef", 0),
("1.0a1.post5.dev6+deadbeef", 0),
("1.0rc4+deadbeef", 0),
("1.0.post5+deadbeef", 0),
("1!1.0+deadbeef", 1),
("1!1.0.dev6+deadbeef", 1),
("1!1.0a1+deadbeef", 1),
("1!1.0a1.post5+deadbeef", 1),
("1!1.0a1.post5.dev6+deadbeef", 1),
("1!1.0rc4+deadbeef", 1),
("1!1.0.post5+deadbeef", 1),
],
)
def test_version_epoch(self, version: str, epoch: int) -> None:
assert Version(version).epoch == epoch
@pytest.mark.parametrize(
("version", "release"),
[
("1.0", (1, 0)),
("1.0.dev0", (1, 0)),
("1.0.dev6", (1, 0)),
("1.0a1", (1, 0)),
("1.0a1.post5", (1, 0)),
("1.0a1.post5.dev6", (1, 0)),
("1.0rc4", (1, 0)),
("1.0.post5", (1, 0)),
("1!1.0", (1, 0)),
("1!1.0.dev6", (1, 0)),
("1!1.0a1", (1, 0)),
("1!1.0a1.post5", (1, 0)),
("1!1.0a1.post5.dev6", (1, 0)),
("1!1.0rc4", (1, 0)),
("1!1.0.post5", (1, 0)),
("1.0+deadbeef", (1, 0)),
("1.0.dev6+deadbeef", (1, 0)),
("1.0a1+deadbeef", (1, 0)),
("1.0a1.post5+deadbeef", (1, 0)),
("1.0a1.post5.dev6+deadbeef", (1, 0)),
("1.0rc4+deadbeef", (1, 0)),
("1.0.post5+deadbeef", (1, 0)),
("1!1.0+deadbeef", (1, 0)),
("1!1.0.dev6+deadbeef", (1, 0)),
("1!1.0a1+deadbeef", (1, 0)),
("1!1.0a1.post5+deadbeef", (1, 0)),
("1!1.0a1.post5.dev6+deadbeef", (1, 0)),
("1!1.0rc4+deadbeef", (1, 0)),
("1!1.0.post5+deadbeef", (1, 0)),
],
)
def test_version_release(self, version: str, release: tuple[int, int]) -> None:
assert Version(version).release == release
@pytest.mark.parametrize(
("version", "local"),
[
("1.0", None),
("1.0.dev0", None),
("1.0.dev6", None),
("1.0a1", None),
("1.0a1.post5", None),
("1.0a1.post5.dev6", None),
("1.0rc4", None),
("1.0.post5", None),
("1!1.0", None),
("1!1.0.dev6", None),
("1!1.0a1", None),
("1!1.0a1.post5", None),
("1!1.0a1.post5.dev6", None),
("1!1.0rc4", None),
("1!1.0.post5", None),
("1.0+deadbeef", "deadbeef"),
("1.0.dev6+deadbeef", "deadbeef"),
("1.0a1+deadbeef", "deadbeef"),
("1.0a1.post5+deadbeef", "deadbeef"),
("1.0a1.post5.dev6+deadbeef", "deadbeef"),
("1.0rc4+deadbeef", "deadbeef"),
("1.0.post5+deadbeef", "deadbeef"),
("1!1.0+deadbeef", "deadbeef"),
("1!1.0.dev6+deadbeef", "deadbeef"),
("1!1.0a1+deadbeef", "deadbeef"),
("1!1.0a1.post5+deadbeef", "deadbeef"),
("1!1.0a1.post5.dev6+deadbeef", "deadbeef"),
("1!1.0rc4+deadbeef", "deadbeef"),
("1!1.0.post5+deadbeef", "deadbeef"),
],
)
def test_version_local(self, version: str, local: str | None) -> None:
assert Version(version).local == local
@pytest.mark.parametrize(
("version", "pre"),
[
("1.0", None),
("1.0.dev0", None),
("1.0.dev6", None),
("1.0a1", ("a", 1)),
("1.0a1.post5", ("a", 1)),
("1.0a1.post5.dev6", ("a", 1)),
("1.0rc4", ("rc", 4)),
("1.0.post5", None),
("1!1.0", None),
("1!1.0.dev6", None),
("1!1.0a1", ("a", 1)),
("1!1.0a1.post5", ("a", 1)),
("1!1.0a1.post5.dev6", ("a", 1)),
("1!1.0rc4", ("rc", 4)),
("1!1.0.post5", None),
("1.0+deadbeef", None),
("1.0.dev6+deadbeef", None),
("1.0a1+deadbeef", ("a", 1)),
("1.0a1.post5+deadbeef", ("a", 1)),
("1.0a1.post5.dev6+deadbeef", ("a", 1)),
("1.0rc4+deadbeef", ("rc", 4)),
("1.0.post5+deadbeef", None),
("1!1.0+deadbeef", None),
("1!1.0.dev6+deadbeef", None),
("1!1.0a1+deadbeef", ("a", 1)),
("1!1.0a1.post5+deadbeef", ("a", 1)),
("1!1.0a1.post5.dev6+deadbeef", ("a", 1)),
("1!1.0rc4+deadbeef", ("rc", 4)),
("1!1.0.post5+deadbeef", None),
],
)
def test_version_pre(self, version: str, pre: None | tuple[str, int]) -> None:
assert Version(version).pre == pre
@pytest.mark.parametrize(
("version", "expected"),
[
("1.0.dev0", True),
("1.0.dev1", True),
("1.0a1.dev1", True),
("1.0b1.dev1", True),
("1.0c1.dev1", True),
("1.0rc1.dev1", True),
("1.0a1", True),
("1.0b1", True),
("1.0c1", True),
("1.0rc1", True),
("1.0a1.post1.dev1", True),
("1.0b1.post1.dev1", True),
("1.0c1.post1.dev1", True),
("1.0rc1.post1.dev1", True),
("1.0a1.post1", True),
("1.0b1.post1", True),
("1.0c1.post1", True),
("1.0rc1.post1", True),
("1.0", False),
("1.0+dev", False),
("1.0.post1", False),
("1.0.post1+dev", False),
],
)
def test_version_is_prerelease(self, version: str, expected: bool) -> None:
assert Version(version).is_prerelease is expected
@pytest.mark.parametrize(
("version", "dev"),
[
("1.0", None),
("1.0.dev0", 0),
("1.0.dev6", 6),
("1.0a1", None),
("1.0a1.post5", None),
("1.0a1.post5.dev6", 6),
("1.0rc4", None),
("1.0.post5", None),
("1!1.0", None),
("1!1.0.dev6", 6),
("1!1.0a1", None),
("1!1.0a1.post5", None),
("1!1.0a1.post5.dev6", 6),
("1!1.0rc4", None),
("1!1.0.post5", None),
("1.0+deadbeef", None),
("1.0.dev6+deadbeef", 6),
("1.0a1+deadbeef", None),
("1.0a1.post5+deadbeef", None),
("1.0a1.post5.dev6+deadbeef", 6),
("1.0rc4+deadbeef", None),
("1.0.post5+deadbeef", None),
("1!1.0+deadbeef", None),
("1!1.0.dev6+deadbeef", 6),
("1!1.0a1+deadbeef", None),
("1!1.0a1.post5+deadbeef", None),
("1!1.0a1.post5.dev6+deadbeef", 6),
("1!1.0rc4+deadbeef", None),
("1!1.0.post5+deadbeef", None),
],
)
def test_version_dev(self, version: str, dev: int | None) -> None:
assert Version(version).dev == dev
@pytest.mark.parametrize(
("version", "expected"),
[
("1.0", False),
("1.0.dev0", True),
("1.0.dev6", True),
("1.0a1", False),
("1.0a1.post5", False),
("1.0a1.post5.dev6", True),
("1.0rc4", False),
("1.0.post5", False),
("1!1.0", False),
("1!1.0.dev6", True),
("1!1.0a1", False),
("1!1.0a1.post5", False),
("1!1.0a1.post5.dev6", True),
("1!1.0rc4", False),
("1!1.0.post5", False),
("1.0+deadbeef", False),
("1.0.dev6+deadbeef", True),
("1.0a1+deadbeef", False),
("1.0a1.post5+deadbeef", False),
("1.0a1.post5.dev6+deadbeef", True),
("1.0rc4+deadbeef", False),
("1.0.post5+deadbeef", False),
("1!1.0+deadbeef", False),
("1!1.0.dev6+deadbeef", True),
("1!1.0a1+deadbeef", False),
("1!1.0a1.post5+deadbeef", False),
("1!1.0a1.post5.dev6+deadbeef", True),
("1!1.0rc4+deadbeef", False),
("1!1.0.post5+deadbeef", False),
],
)
def test_version_is_devrelease(self, version: str, expected: bool) -> None:
assert Version(version).is_devrelease is expected
@pytest.mark.parametrize(
("version", "post"),
[
("1.0", None),
("1.0.dev0", None),
("1.0.dev6", None),
("1.0a1", None),
("1.0a1.post5", 5),
("1.0a1.post5.dev6", 5),
("1.0rc4", None),
("1.0.post5", 5),
("1!1.0", None),
("1!1.0.dev6", None),
("1!1.0a1", None),
("1!1.0a1.post5", 5),
("1!1.0a1.post5.dev6", 5),
("1!1.0rc4", None),
("1!1.0.post5", 5),
("1.0+deadbeef", None),
("1.0.dev6+deadbeef", None),
("1.0a1+deadbeef", None),
("1.0a1.post5+deadbeef", 5),
("1.0a1.post5.dev6+deadbeef", 5),
("1.0rc4+deadbeef", None),
("1.0.post5+deadbeef", 5),
("1!1.0+deadbeef", None),
("1!1.0.dev6+deadbeef", None),
("1!1.0a1+deadbeef", None),
("1!1.0a1.post5+deadbeef", 5),
("1!1.0a1.post5.dev6+deadbeef", 5),
("1!1.0rc4+deadbeef", None),
("1!1.0.post5+deadbeef", 5),
],
)
def test_version_post(self, version: str, post: int | None) -> None:
assert Version(version).post == post
@pytest.mark.parametrize(
("version", "expected"),
[
("1.0.dev1", False),
("1.0", False),
("1.0+foo", False),
("1.0.post1.dev1", True),
("1.0.post1", True),
],
)
def test_version_is_postrelease(self, version: str, expected: bool) -> None:
assert Version(version).is_postrelease is expected
@pytest.mark.parametrize(
("left", "right", "op"),
# Below we'll generate every possible combination of VERSIONS that
# should be True for the given operator
itertools.chain.from_iterable(
# Verify that the less than (<) operator works correctly
[
[(x, y, operator.lt) for y in VERSIONS[i + 1 :]]
for i, x in enumerate(VERSIONS)
]
+
# Verify that the less than equal (<=) operator works correctly
[
[(x, y, operator.le) for y in VERSIONS[i:]]
for i, x in enumerate(VERSIONS)
]
+
# Verify that the equal (==) operator works correctly
[[(x, x, operator.eq) for x in VERSIONS]]
+
# Verify that the not equal (!=) operator works correctly
[
[(x, y, operator.ne) for j, y in enumerate(VERSIONS) if i != j]
for i, x in enumerate(VERSIONS)
]
+
# Verify that the greater than equal (>=) operator works correctly
[
[(x, y, operator.ge) for y in VERSIONS[: i + 1]]
for i, x in enumerate(VERSIONS)
]
+
# Verify that the greater than (>) operator works correctly
[
[(x, y, operator.gt) for y in VERSIONS[:i]]
for i, x in enumerate(VERSIONS)
]
),
)
def test_comparison_true(
self, left: str, right: str, op: Callable[[Version, Version], bool]
) -> None:
assert op(Version(left), Version(right))
@pytest.mark.parametrize(
("left", "right", "op"),
# Below we'll generate every possible combination of VERSIONS that
# should be False for the given operator
itertools.chain.from_iterable(
# Verify that the less than (<) operator works correctly
[
[(x, y, operator.lt) for y in VERSIONS[: i + 1]]
for i, x in enumerate(VERSIONS)
]
+
# Verify that the less than equal (<=) operator works correctly
[
[(x, y, operator.le) for y in VERSIONS[:i]]
for i, x in enumerate(VERSIONS)
]
+
# Verify that the equal (==) operator works correctly
[
[(x, y, operator.eq) for j, y in enumerate(VERSIONS) if i != j]
for i, x in enumerate(VERSIONS)
]
+
# Verify that the not equal (!=) operator works correctly
[[(x, x, operator.ne) for x in VERSIONS]]
+
# Verify that the greater than equal (>=) operator works correctly
[
[(x, y, operator.ge) for y in VERSIONS[i + 1 :]]
for i, x in enumerate(VERSIONS)
]
+
# Verify that the greater than (>) operator works correctly
[
[(x, y, operator.gt) for y in VERSIONS[i:]]
for i, x in enumerate(VERSIONS)
]
),
)
def test_comparison_false(
self, left: str, right: str, op: Callable[[Version, Version], bool]
) -> None:
assert not op(Version(left), Version(right))
@pytest.mark.parametrize("op", ["lt", "le", "eq", "ge", "gt", "ne"])
def test_dunder_op_returns_notimplemented(self, op: str) -> None:
method = getattr(Version, f"__{op}__")
assert method(Version("1"), 1) is NotImplemented
@pytest.mark.parametrize(("op", "expected"), [("eq", False), ("ne", True)])
def test_compare_other(self, op: str, expected: bool) -> None:
other = pretend.stub(**{f"__{op}__": lambda _: NotImplemented})
assert getattr(operator, op)(Version("1"), other) is expected
def test_major_version(self) -> None:
assert Version("2.1.0").major == 2
def test_minor_version(self) -> None:
assert Version("2.1.0").minor == 1
assert Version("2").minor == 0
def test_micro_version(self) -> None:
assert Version("2.1.3").micro == 3
assert Version("2.1").micro == 0
assert Version("2").micro == 0
# Tests for replace() method
def test_replace_no_args(self) -> None:
"""replace() with no arguments should return an equivalent version"""
v = Version("1.2.3a1.post2.dev3+local")
v_replaced = replace(v)
assert v == v_replaced
assert str(v) == str(v_replaced)
def test_replace_epoch(self) -> None:
v = Version("1.2.3")
assert str(replace(v, epoch=2)) == "2!1.2.3"
assert replace(v, epoch=0).epoch == 0
v_with_epoch = Version("1!1.2.3")
assert str(replace(v_with_epoch, epoch=2)) == "2!1.2.3"
assert str(replace(v_with_epoch, epoch=None)) == "1.2.3"
def test_replace_release_tuple(self) -> None:
v = Version("1.2.3")
assert str(replace(v, release=(2, 0, 0))) == "2.0.0"
assert str(replace(v, release=(1,))) == "1"
assert str(replace(v, release=(1, 2, 3, 4, 5))) == "1.2.3.4.5"
def test_replace_release_none(self) -> None:
v = Version("1.2.3")
assert str(replace(v, release=None)) == "0"
def test_replace_pre_alpha(self) -> None:
v = Version("1.2.3")
assert str(replace(v, pre=("a", 1))) == "1.2.3a1"
assert str(replace(v, pre=("a", 0))) == "1.2.3a0"
def test_replace_pre_alpha_none(self) -> None:
v = Version("1.2.3a1")
assert str(replace(v, pre=None)) == "1.2.3"
def test_replace_pre_beta(self) -> None:
v = Version("1.2.3")
assert str(replace(v, pre=("b", 1))) == "1.2.3b1"
assert str(replace(v, pre=("b", 0))) == "1.2.3b0"
def test_replace_pre_beta_none(self) -> None:
v = Version("1.2.3b1")
assert str(replace(v, pre=None)) == "1.2.3"
def test_replace_pre_rc(self) -> None:
v = Version("1.2.3")
assert str(replace(v, pre=("rc", 1))) == "1.2.3rc1"
assert str(replace(v, pre=("rc", 0))) == "1.2.3rc0"
def test_replace_pre_rc_none(self) -> None:
v = Version("1.2.3rc1")
assert str(replace(v, pre=None)) == "1.2.3"
def test_replace_post(self) -> None:
v = Version("1.2.3")
assert str(replace(v, post=1)) == "1.2.3.post1"
assert str(replace(v, post=0)) == "1.2.3.post0"
def test_replace_post_none(self) -> None:
v = Version("1.2.3.post1")
assert str(replace(v, post=None)) == "1.2.3"
def test_replace_dev(self) -> None:
v = Version("1.2.3")
assert str(replace(v, dev=1)) == "1.2.3.dev1"
assert str(replace(v, dev=0)) == "1.2.3.dev0"
def test_replace_dev_none(self) -> None:
v = Version("1.2.3.dev1")
assert str(replace(v, dev=None)) == "1.2.3"
def test_replace_local_string(self) -> None:
v = Version("1.2.3")
assert str(replace(v, local="abc")) == "1.2.3+abc"
assert str(replace(v, local="abc.123")) == "1.2.3+abc.123"
assert str(replace(v, local="abc-123")) == "1.2.3+abc.123"
def test_replace_local_none(self) -> None:
v = Version("1.2.3+local")
assert str(replace(v, local=None)) == "1.2.3"
def test_replace_multiple_components(self) -> None:
v = Version("1.2.3")
assert str(replace(v, pre=("a", 1), post=1)) == "1.2.3a1.post1"
assert str(replace(v, release=(2, 0, 0), pre=("b", 2), dev=1)) == "2.0.0b2.dev1"
assert str(replace(v, epoch=1, release=(3, 0), local="abc")) == "1!3.0+abc"
def test_replace_clear_all_optional(self) -> None:
v = Version("1!1.2.3a1.post2.dev3+local")
cleared = replace(v, epoch=None, pre=None, post=None, dev=None, local=None)
assert str(cleared) == "1.2.3"
def test_replace_preserves_comparison(self) -> None:
v1 = Version("1.2.3")
v2 = Version("1.2.4")
v1_new = replace(v1, release=(1, 2, 4))
assert v1_new == v2
assert v1 < v2
assert v1_new >= v2
def test_replace_preserves_hash(self) -> None:
v1 = Version("1.2.3")
v2 = replace(v1, release=(1, 2, 3))
assert hash(v1) == hash(v2)
v3 = replace(v1, release=(2, 0, 0))
assert hash(v1) != hash(v3)
def test_replace_returns_same_instance_when_unchanged(self) -> None:
"""replace() returns the exact same object when no components change"""
v = Version("1.2.3a1.post2.dev3+local")
assert replace(v) is v
assert replace(v, epoch=0) is v
assert replace(v, release=(1, 2, 3)) is v
assert replace(v, pre=("a", 1)) is v
assert replace(v, post=2) is v
assert replace(v, dev=3) is v
assert replace(v, local="local") is v
def test_replace_change_pre_type(self) -> None:
"""Can change from one pre-release type to another"""
v = Version("1.2.3a1")
assert str(replace(v, pre=("b", 2))) == "1.2.3b2"
assert str(replace(v, pre=("rc", 1))) == "1.2.3rc1"
v2 = Version("1.2.3rc5")
assert str(replace(v2, pre=("a", 0))) == "1.2.3a0"
def test_replace_invalid_epoch_type(self) -> None:
v = Version("1.2.3")
with pytest.raises(InvalidVersion, match="epoch must be non-negative"):
replace(v, epoch="1") # type: ignore[arg-type]
def test_replace_invalid_post_type(self) -> None:
v = Version("1.2.3")
with pytest.raises(InvalidVersion, match="post must be non-negative"):
replace(v, post="1") # type: ignore[arg-type]
def test_replace_invalid_dev_type(self) -> None:
v = Version("1.2.3")
with pytest.raises(InvalidVersion, match="dev must be non-negative"):
replace(v, dev="1") # type: ignore[arg-type]
def test_replace_invalid_epoch_negative(self) -> None:
v = Version("1.2.3")
with pytest.raises(InvalidVersion, match="epoch must be non-negative"):
replace(v, epoch=-1)
def test_replace_invalid_release_empty(self) -> None:
v = Version("1.2.3")
with pytest.raises(InvalidVersion, match="release must be a non-empty tuple"):
replace(v, release=())
def test_replace_invalid_release_tuple_content(self) -> None:
v = Version("1.2.3")
with pytest.raises(
InvalidVersion, match="release must be a non-empty tuple of non-negative"
):
replace(v, release=(1, -2, 3))
def test_replace_invalid_pre_negative(self) -> None:
v = Version("1.2.3")
with pytest.raises(InvalidVersion, match="pre must be a tuple"):
replace(v, pre=("a", -1))
def test_replace_invalid_pre_type(self) -> None:
v = Version("1.2.3")
with pytest.raises(InvalidVersion, match="pre must be a tuple"):
replace(v, pre=("x", 1)) # type: ignore[arg-type]
def test_replace_invalid_pre_format(self) -> None:
v = Version("1.2.3")
with pytest.raises(InvalidVersion, match="pre must be a tuple"):
replace(v, pre="a1") # type: ignore[arg-type]
with pytest.raises(InvalidVersion, match="pre must be a tuple"):
replace(v, pre=("a",)) # type: ignore[arg-type]
with pytest.raises(InvalidVersion, match="pre must be a tuple"):
replace(v, pre=("a", 1, 2)) # type: ignore[arg-type]
def test_replace_invalid_post_negative(self) -> None:
v = Version("1.2.3")
with pytest.raises(InvalidVersion, match="post must be non-negative"):
replace(v, post=-1)
def test_replace_invalid_dev_negative(self) -> None:
v = Version("1.2.3")
with pytest.raises(InvalidVersion, match="dev must be non-negative"):
replace(v, dev=-1)
def test_replace_invalid_local_string(self) -> None:
v = Version("1.2.3")
with pytest.raises(
InvalidVersion, match="local must be a valid version string"
):
replace(v, local="abc+123")
with pytest.raises(
InvalidVersion, match="local must be a valid version string"
):
replace(v, local="+abc")
# Taken from hatchling 1.28
def reset_version_parts(version: Version, **kwargs: typing.Any) -> None: # noqa: ANN401
# https://github.com/pypa/packaging/blob/20.9/packaging/version.py#L301-L310
internal_version = version._version
parts: dict[str, typing.Any] = {}
ordered_part_names = ("epoch", "release", "pre", "post", "dev", "local")
reset = False
for part_name in ordered_part_names:
if reset:
parts[part_name] = kwargs.get(part_name)
elif part_name in kwargs:
parts[part_name] = kwargs[part_name]
reset = True
else:
parts[part_name] = getattr(internal_version, part_name)
version._version = type(internal_version)(**parts)
# These will be deprecated in 26.1, and removed in the future
def test_deprecated__version() -> None:
v = Version("1.2.3")
with pytest.warns(DeprecationWarning, match="is private"):
assert v._version.release == (1, 2, 3)
def test_hatchling_usage__version() -> None:
v = Version("2.3.4")
with pytest.warns(DeprecationWarning, match="is private"):
reset_version_parts(v, post=("post", 1))
assert v == Version("2.3.4.post1")
packaging-26.0/PKG-INFO 0000644 0000000 0000000 00000006355 00000000000 011362 0 ustar 00 Metadata-Version: 2.4
Name: packaging
Version: 26.0
Summary: Core utilities for Python packages
Author-email: Donald Stufft
Requires-Python: >=3.8
Description-Content-Type: text/x-rst
License-Expression: Apache-2.0 OR BSD-2-Clause
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Programming Language :: Python :: Implementation :: PyPy
Classifier: Typing :: Typed
License-File: LICENSE
License-File: LICENSE.APACHE
License-File: LICENSE.BSD
Project-URL: Documentation, https://packaging.pypa.io/
Project-URL: Source, https://github.com/pypa/packaging
packaging
=========
.. start-intro
Reusable core utilities for various Python Packaging
`interoperability specifications `_.
This library provides utilities that implement the interoperability
specifications which have clearly one correct behaviour (eg: :pep:`440`)
or benefit greatly from having a single shared implementation (eg: :pep:`425`).
.. end-intro
The ``packaging`` project includes the following: version handling, specifiers,
markers, requirements, tags, metadata, lockfiles, utilities.
Documentation
-------------
The `documentation`_ provides information and the API for the following:
- Version Handling
- Specifiers
- Markers
- Requirements
- Tags
- Metadata
- Lockfiles
- Utilities
Installation
------------
Use ``pip`` to install these utilities::
pip install packaging
The ``packaging`` library uses calendar-based versioning (``YY.N``).
Discussion
----------
If you run into bugs, you can file them in our `issue tracker`_.
You can also join ``#pypa`` on Freenode to ask questions or get involved.
.. _`documentation`: https://packaging.pypa.io/
.. _`issue tracker`: https://github.com/pypa/packaging/issues
Code of Conduct
---------------
Everyone interacting in the packaging project's codebases, issue trackers, chat
rooms, and mailing lists is expected to follow the `PSF Code of Conduct`_.
.. _PSF Code of Conduct: https://github.com/pypa/.github/blob/main/CODE_OF_CONDUCT.md
Contributing
------------
The ``CONTRIBUTING.rst`` file outlines how to contribute to this project as
well as how to report a potential security issue. The documentation for this
project also covers information about `project development`_ and `security`_.
.. _`project development`: https://packaging.pypa.io/en/latest/development/
.. _`security`: https://packaging.pypa.io/en/latest/security/
Project History
---------------
Please review the ``CHANGELOG.rst`` file or the `Changelog documentation`_ for
recent changes and project history.
.. _`Changelog documentation`: https://packaging.pypa.io/en/latest/changelog/