imbajin commented on code in PR #3326: URL: https://github.com/apache/hugegraph/pull/3326#discussion_r4260772651
########## .github/scripts/test_dependency_snapshot.py: ########## @@ -0,0 +1,302 @@ +#!/usr/bin/env python3 +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Native-parser regression fixtures and local-only writer protocol controls.""" + +import copy +from contextlib import redirect_stdout +import datetime +import hashlib +import importlib.util +import io +import json +import os +from pathlib import Path +import tempfile +import textwrap +import unittest +import urllib.error +import warnings +import zipfile +from unittest.mock import patch +from urllib.parse import urlsplit + + +def load_module(path, name): + spec = importlib.util.spec_from_file_location(name, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +producer = load_module(Path(__file__).with_name('dependency-snapshot.py'), 'producer') + + +def artifact(identifier, **fields): + return dict(id=identifier, groupId='org.example', artifactId=identifier, version='1.0', types=['jar'], **fields) + + +class SnapshotTest(unittest.TestCase): + + def setUp(self): + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + self.root = Path(temporary.name) + workflow = Path(__file__).resolve().parents[1] / 'workflows/submit-dependencies.yml' + # Only the fixed workflow program is loaded as code. Artifacts remain JSON data. + program = workflow.read_text().split(" python3 -I - <<'PY'\n", 1)[1].split('\n PY', 1)[0] + script = self.root / 'fixed-writer.py' + script.write_text(textwrap.dedent(program)) + self.writer = load_module(script, 'writer') + self.env = {'EXPECTED_REPOSITORY': 'apache/hugegraph', 'EXPECTED_SHA': 'a' * 40, + 'RUN_ID': '321', 'RUN_ATTEMPT': '2', 'ARTIFACT_ID': '789', 'RUNNER_TEMP': str(self.root), + 'SNAPSHOT_TOKEN': 'public-synthetic-sentinel'} + directory = self.root / 'dependency-snapshot' + directory.mkdir() + self.source = directory / 'snapshot.json' + graph = {'graphName': 'module', 'artifacts': [artifact('root'), artifact('one'), artifact('two')], + 'dependencies': [{'from': 'root', 'to': 'one'}, {'from': 'one', 'to': 'two'}]} + now = datetime.datetime.now(datetime.timezone.utc) + self.snapshot = {'version': 0, 'sha': self.env['EXPECTED_SHA'], 'ref': 'refs/heads/master', + 'job': {'id': '321', 'correlator': producer.CORRELATOR, + 'html_url': 'https://github.com/apache/hugegraph/actions/runs/321'}, + 'detector': producer.DETECTOR, 'metadata': {'serializer': producer.SERIALIZER, + 'producer': 'generate', 'run_attempt': '2'}, + 'scanned': now.isoformat(), 'manifests': {'module': producer.manifest(graph, 'pom.xml')}} + self.responses = { + 'actions/runs/321/attempts/2': {'id': 321, 'run_attempt': 2, 'head_sha': 'a' * 40, + 'head_branch': 'master', 'event': 'push', 'repository': {'full_name': 'apache/hugegraph'}, + 'path': '.github/workflows/submit-dependencies.yml', + 'run_started_at': (now - datetime.timedelta(minutes=2)).isoformat()}, + 'actions/runs/321/attempts/2/jobs?per_page=100': {'total_count': 3, + 'jobs': [{'name': 'generate', 'conclusion': 'success', 'status': 'completed', + 'run_id': 321, 'head_sha': 'a' * 40}]}, + 'actions/artifacts/789': {'id': 789, 'expired': False, 'name': 'dependency-snapshot-321-2', + 'created_at': now.isoformat(), + 'workflow_run': {'id': 321, 'head_sha': 'a' * 40, 'head_branch': 'master'}}, + 'git/trees/' + 'a' * 40 + '?recursive=1': {'truncated': False, + 'tree': [{'path': 'pom.xml', 'type': 'blob', 'mode': '100644'}]}, + 'git/ref/heads/master': {'object': {'sha': 'a' * 40}}, + 'dependency-graph/snapshots': {'result': 'SUCCESS'}, + } + self.posts = [] + self.blob_headers = [] + + def run_writer(self, snapshot=None, raw=None, archive=None, artifact_changes=None): + if archive is None: + payload = raw if raw is not None else json.dumps(snapshot or self.snapshot) + archive = self.zip_bytes([('snapshot.json', payload)]) + self.responses['actions/artifacts/789'].update(size_in_bytes=len(archive), + digest='sha256:' + hashlib.sha256(archive).hexdigest()) + self.responses['actions/artifacts/789'].update(artifact_changes or {}) + + def open_request(request, timeout): + url = urlsplit(request.full_url) + self.assertEqual('https', url.scheme) + if url.netloc == 'storage.blob.core.windows.net': + self.blob_headers.append(dict(request.header_items())) + self.assertIsNone(request.get_header('Authorization')) + response = io.BytesIO(archive) + response.status = 200 + return response + self.assertEqual('api.github.com', url.netloc) + self.assertTrue(url.path.startswith('/repos/apache/hugegraph/')) + self.assertEqual('Bearer public-synthetic-sentinel', request.get_header('Authorization')) + path = url.path.removeprefix('/repos/apache/hugegraph/') + ('?' + url.query if url.query else '') + if path == 'actions/artifacts/789/zip': + raise urllib.error.HTTPError(request.full_url, 302, 'Found', + {'Location': 'https://storage.blob.core.windows.net/archive.zip?sig=public'}, io.BytesIO()) + if request.data is not None: + self.assertEqual('dependency-graph/snapshots', path) + self.posts.append(json.loads(request.data)) + response = io.BytesIO(json.dumps(self.responses[path]).encode()) + response.status = 201 if request.data is not None else 200 + return response + + opener = self.writer.urllib.request.OpenerDirector() + opener.open = open_request + with patch.dict(os.environ, self.env), patch.object(self.writer.urllib.request, + 'build_opener', return_value=opener): + with redirect_stdout(io.StringIO()): + self.writer.main() + + @staticmethod + def zip_bytes(entries, mode=None): + output = io.BytesIO() + with warnings.catch_warnings(): + warnings.simplefilter('ignore', UserWarning) + with zipfile.ZipFile(output, 'w', compression=zipfile.ZIP_DEFLATED) as archive: + for name, data in entries: + entry = zipfile.ZipInfo(name) + entry.compress_type = zipfile.ZIP_DEFLATED + if mode is not None: + entry.create_system = 3 + entry.external_attr = mode << 16 + archive.writestr(entry, data) + return output.getvalue() + + def test_native_package_url_encoding(self): + # Expected strings were captured from the pinned action's actual parser. + cases = [ + (dict(groupId='org.图//组/', artifactId='测试/名@', version='1+2/slash~', + classifiers=['测试 c/+~*'], types=['jar']), + 'pkg:maven/org.%E5%9B%BE/%E7%BB%84/%E6%B5%8B%E8%AF%95%2F%E5%90%8D%40@1+2%2Fslash~' + '?classifier=%E6%B5%8B%E8%AF%95%20c%2F%2B%7E*&type=jar'), + (dict(groupId="g:!/x~*'()", artifactId="n:!~*'()", version="v:!~*'()+", + classifiers=[' c/+~* '], types=[' jar ', 'war']), + "pkg:maven/g:!/x~*'()/n%3A!~*'()@v:!~*'()+?classifier=c%2F%2B%7E*&type=jar"), + ] + for value, expected in cases: + self.assertEqual(expected, producer.package_url(value)) + + def test_native_cycle_alias_scope_and_direct_precedence(self): + graph = {'graphName': 'module', 'artifacts': [artifact('root'), artifact('one', scopes=['test']), + dict(artifact('one'), id='alias', scopes=['provided']), artifact('two'), artifact('three')], + 'dependencies': [{'from': 'root', 'to': 'one'}, {'from': 'one', 'to': 'two'}, + {'from': 'two', 'to': 'one'}, {'from': 'alias', 'to': 'three'}, + {'from': 'root', 'to': 'two'}]} + resolved = producer.manifest(graph, 'pom.xml')['resolved'] + one, two, three = [f'pkg:maven/org.example/{name}@1.0?type=jar' for name in ['one', 'two', 'three']] + self.assertEqual({'package_url': one, 'relationship': 'direct', 'scope': 'runtime', + 'dependencies': [two, three]}, resolved[one]) + self.assertEqual({'direct'}, {entry['relationship'] for entry in resolved.values()}) Review Comment: Added separate graph fixtures for an indirect-only chain and for a dependency reachable by both direct and indirect paths. Their complete manifest assertions reject both an all-direct serializer and an indirect-wins serializer. The original suite still passes, and the published two-file update matches the source checked by the three independent reviewers. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
