From 0c6c596ac9c935564998c5a666ea8cd9dd6ef927 Mon Sep 17 00:00:00 2001 From: Kumar Aditya <59607654+kumaraditya303@users.noreply.github.com> Date: Tue, 4 Jan 2022 16:20:33 +0530 Subject: [PATCH] bpo-46119: Add hash test for ensurepip packages --- Lib/test/support/__init__.py | 3 +-- Lib/test/test_ensurepip.py | 25 +++++++++++++++++++++++-- 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/Lib/test/support/__init__.py b/Lib/test/support/__init__.py index f8faa41ad439c4..bd3527ed4d59f3 100644 --- a/Lib/test/support/__init__.py +++ b/Lib/test/support/__init__.py @@ -548,8 +548,7 @@ def open_urlresource(url, *args, **kw): check = kw.pop('check', None) - filename = urllib.parse.urlparse(url)[2].split('/')[-1] # '/': it's URL! - + filename = urllib.parse.urlparse(url).path.replace('/', '_') # '/': it's URL! fn = os.path.join(TEST_DATA_DIR, filename) def check_valid_file(fn): diff --git a/Lib/test/test_ensurepip.py b/Lib/test/test_ensurepip.py index bfca0cd7fbe483..44718829a3aa87 100644 --- a/Lib/test/test_ensurepip.py +++ b/Lib/test/test_ensurepip.py @@ -6,12 +6,33 @@ import test.support import unittest import unittest.mock - +import json import ensurepip import ensurepip._uninstall - +import hashlib class TestPackages(unittest.TestCase): + + def test_packages_hash(self): + packages = ensurepip._get_packages() + for name, package in packages.items(): + with test.support.open_urlresource(f"https://pypi.org/pypi/{name}/{package.version}/json") as data: + expected_sha256 = json.load(data)["releases"][package.version][0]["digests"]["sha256"] + if package.wheel_name: + # Use bundled wheel package + from ensurepip import _bundled + from importlib import resources + wheel_name = package.wheel_name + whl = (resources.files(_bundled) / wheel_name).read_bytes() + else: + # Use the wheel package directory + with open(package.wheel_path, "rb") as fp: + whl = fp.read() + self.assertEqual( + hashlib.sha256(whl).hexdigest(), + expected_sha256, + ) + def touch(self, directory, filename): fullname = os.path.join(directory, filename) open(fullname, "wb").close()