"""Offline Maven dependency GAV, scope matrix, mediation, exclusions & BOM import verifier for Ch09 (dependencies)."""
import json
import xml.etree.ElementTree as ET
from collections import deque
VERSION = "CPython 3.12.14 offline Maven POM/lifecycle/dependency verifier (mvn CLI absent)"
def check(name, summary, expected, actual):
return {
"name": name,
"summary": summary,
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = []
# Case 1: GAV coordinate & Scope packaging rules
dep_xml = """
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
"""
root = ET.fromstring(dep_xml)
parsed_deps = [
{
"ga": f"{d.findtext('groupId')}:{d.findtext('artifactId')}",
"version": d.findtext("version"),
"scope": d.findtext("scope") or "compile",
}
for d in root.findall("dependency")
]
packaging_rules = {"compile": True, "provided": False, "runtime": True, "test": False}
cases.append(
check(
"gav_and_scope_packaging_matrix",
"Verify default compile scope, 5 standard scopes, and packaging inclusion per scope",
{
"parsed": [
{"ga": "org.apache.commons:commons-lang3", "version": "3.12.0", "scope": "compile"},
{"ga": "junit:junit", "version": "4.12", "scope": "test"},
],
"packaged_scopes": ["compile", "runtime"],
"excluded_from_package": ["provided", "test"],
},
{
"parsed": parsed_deps,
"packaged_scopes": [k for k, v in packaging_rules.items() if v],
"excluded_from_package": [k for k, v in packaging_rules.items() if not v],
},
)
)
# Case 2: Transitive scope propagation matrix (direct x transitive)
# Follows Maven official specification (and notes provided/test non-transitivity)
matrix = {
"compile": {"compile": "compile", "provided": "-", "runtime": "runtime", "test": "-"},
"provided": {"compile": "provided", "provided": "-", "runtime": "provided", "test": "-"},
"runtime": {"compile": "runtime", "provided": "-", "runtime": "runtime", "test": "-"},
"test": {"compile": "test", "provided": "-", "runtime": "test", "test": "-"},
}
cases.append(
check(
"transitive_scope_propagation_matrix",
"Verify Maven transitive scope resolution across compile/provided/runtime/test combinations",
{
"compile_x_compile": "compile",
"compile_x_runtime": "runtime",
"compile_x_provided": "-",
"compile_x_test": "-",
"runtime_x_compile": "runtime",
"provided_x_compile": "provided",
},
{
"compile_x_compile": matrix["compile"]["compile"],
"compile_x_runtime": matrix["compile"]["runtime"],
"compile_x_provided": matrix["compile"]["provided"],
"compile_x_test": matrix["compile"]["test"],
"runtime_x_compile": matrix["runtime"]["compile"],
"provided_x_compile": matrix["provided"]["compile"],
},
)
)
# Case 3: Dependency mediation (nearest-definition-wins + first-declaration-wins) + exclusions + optional
# Graph:
# root -> A(1.0) -> B(1.0) -> X(2.0) [depth 3]
# root -> C(1.0) -> X(1.5) [depth 2 -> wins by nearest!]
# root -> D(1.0) -> Y(1.0) [depth 2, declared first -> wins!]
# root -> E(1.0) -> Y(2.0) [depth 2, declared second]
# root -> F(1.0) [excludes Z] -> Z(1.0)
# root -> G(1.0) -> OPT(1.0, optional=True)
graph = {
"root": [("A", "1.0", set(), False), ("C", "1.0", set(), False), ("D", "1.0", set(), False), ("E", "1.0", set(), False), ("F", "1.0", {"Z"}, False), ("G", "1.0", set(), False)],
"A:1.0": [("B", "1.0", set(), False)],
"B:1.0": [("X", "2.0", set(), False)],
"C:1.0": [("X", "1.5", set(), False)],
"D:1.0": [("Y", "1.0", set(), False)],
"E:1.0": [("Y", "2.0", set(), False)],
"F:1.0": [("Z", "1.0", set(), False)],
"G:1.0": [("OPT", "1.0", set(), True)],
}
def resolve_maven(start):
resolved = {}
q = deque([(start, 0, set())])
while q:
node, depth, excl = q.popleft()
for ga, ver, child_excl, is_opt in graph.get(node, []):
if depth > 0 and is_opt:
continue
if ga in excl:
continue
if ga not in resolved:
resolved[ga] = ver
q.append((f"{ga}:{ver}", depth + 1, excl | child_excl))
return resolved
res = resolve_maven("root")
cases.append(
check(
"dependency_mediation_and_exclusions",
"Verify BFS nearest-definition-wins (X=1.5), first-declaration-wins (Y=1.0), <exclusions> (no Z), and <optional> (no OPT)",
{"X": "1.5", "Y": "1.0", "has_Z": False, "has_OPT": False},
{"X": res["X"], "Y": res["Y"], "has_Z": "Z" in res, "has_OPT": "OPT" in res},
)
)
# Case 4: <dependencyManagement> version inheritance & BOM scope=import
dm_xml = """
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.3.20</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.6.4</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
"""
dm_root = ET.fromstring(dm_xml)
managed_versions = {}
boms = []
for d in dm_root.findall("dependencies/dependency"):
ga = f"{d.findtext('groupId')}:{d.findtext('artifactId')}"
if d.findtext("scope") == "import" and d.findtext("type") == "pom":
boms.append(f"{ga}:{d.findtext('version')}")
else:
managed_versions[ga] = d.findtext("version")
child_resolved = managed_versions["org.springframework:spring-core"]
cases.append(
check(
"dependency_management_and_bom_import",
"Parse <dependencyManagement> managed version and BOM <type>pom</type><scope>import</scope>",
{
"child_spring_core_version": "5.3.20",
"imported_boms": ["org.springframework.boot:spring-boot-dependencies:2.6.4"],
},
{
"child_spring_core_version": child_resolved,
"imported_boms": boms,
},
)
)
# Case 5: Repository XML & dependency diagnostic commands
repo_xml = """
<repositories>
<repository>
<id>my-repo</id>
<url>http://repo.example.com/maven2</url>
</repository>
</repositories>
"""
r_el = ET.fromstring(repo_xml).find("repository")
dynamic_tags = {"LATEST", "RELEASE"}
pinned_ok = "3.12.0" not in dynamic_tags
cases.append(
check(
"repo_config_and_dependency_commands",
"Parse custom <repository> XML and verify pinned version practice & diagnostic plugin goals",
{
"repo_id": "my-repo",
"repo_url": "http://repo.example.com/maven2",
"pinned_version_valid": True,
"diagnostic_goals": ["dependency:tree", "dependency:analyze", "dependency:copy-dependencies"],
},
{
"repo_id": r_el.findtext("id"),
"repo_url": r_el.findtext("url"),
"pinned_version_valid": pinned_ok,
"diagnostic_goals": ["dependency:tree", "dependency:analyze", "dependency:copy-dependencies"],
},
)
)
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/maven-dependencies-lab/explore-dependencies.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-dependencies.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2182.zip
课程关联工程包(登记关联25章) · 含当前章节或实例 · mbskycom202612a2175.zip