蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行 Maven Build Profiles 三级作用域与 5 种激活触发条件离线核验

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-build-profiles.py
explore-build-profiles.py182 行
"""Offline Maven build profiles & 5 activation mechanisms verifier for Ch07 (build-profiles)."""
import json
import tempfile
import xml.etree.ElementTree as ET
from pathlib import Path

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: Three profile scopes & environment properties files
    scopes = [
        {"type": "Per Project", "file": "pom.xml"},
        {"type": "Per User", "file": "%USER_HOME%/.m2/settings.xml"},
        {"type": "Global", "file": "%M2_HOME%/conf/settings.xml"},
    ]
    env_files = {
        "normal": "src/main/resources/env.properties",
        "test": "src/main/resources/env.test.properties",
        "prod": "src/main/resources/env.prod.properties",
    }
    cases.append(
        check(
            "profile_scopes_and_env_files",
            "Verify 3 profile definition scopes (project/user/global) and 3 environment property files",
            {"scope_count": 3, "env_file_count": 3, "prod_file": "src/main/resources/env.prod.properties"},
            {"scope_count": len(scopes), "env_file_count": len(env_files), "prod_file": env_files["prod"]},
        )
    )

    # Case 2: Explicit CLI -P activation parsing multi-profile pom.xml
    pom_profiles = """
    <project>
      <profiles>
        <profile>
          <id>test</id>
          <build><plugins><plugin><artifactId>maven-antrun-plugin</artifactId><executions><execution>
            <phase>test</phase><goals><goal>run</goal></goals>
            <configuration><tasks><echo>Using env.test.properties</echo><copy file="src/main/resources/env.test.properties" tofile="${project.build.outputDirectory}/env.properties" overwrite="true"/></tasks></configuration>
          </execution></executions></plugin></plugins></build>
        </profile>
        <profile>
          <id>normal</id>
          <build><plugins><plugin><artifactId>maven-antrun-plugin</artifactId><executions><execution>
            <phase>test</phase><goals><goal>run</goal></goals>
            <configuration><tasks><echo>Using env.properties</echo><copy file="src/main/resources/env.properties" tofile="${project.build.outputDirectory}/env.properties" overwrite="true"/></tasks></configuration>
          </execution></executions></plugin></plugins></build>
        </profile>
        <profile>
          <id>prod</id>
          <build><plugins><plugin><artifactId>maven-antrun-plugin</artifactId><executions><execution>
            <phase>test</phase><goals><goal>run</goal></goals>
            <configuration><tasks><echo>Using env.prod.properties</echo><copy file="src/main/resources/env.prod.properties" tofile="${project.build.outputDirectory}/env.properties" overwrite="true"/></tasks></configuration>
          </execution></executions></plugin></plugins></build>
        </profile>
      </profiles>
    </project>
    """
    root = ET.fromstring(pom_profiles)
    profile_copy = {}
    for p in root.findall("profiles/profile"):
        pid = p.findtext("id")
        copy_el = p.find(".//copy")
        profile_copy[pid] = copy_el.attrib["file"]
    selected_p = "test"
    cases.append(
        check(
            "cli_explicit_profile_activation",
            "Parse multi-profile pom.xml and verify -Ptest / -Pnormal / -Pprod copy targets",
            {
                "profile_ids": ["test", "normal", "prod"],
                "selected_copy_src": "src/main/resources/env.test.properties",
            },
            {
                "profile_ids": list(profile_copy.keys()),
                "selected_copy_src": profile_copy[selected_p],
            },
        )
    )

    # Case 3: settings.xml <activeProfiles> activation
    settings_xml = """
    <settings>
      <activeProfiles>
        <activeProfile>test</activeProfile>
      </activeProfiles>
    </settings>
    """
    s_root = ET.fromstring(settings_xml)
    active_ids = [el.text.strip() for el in s_root.findall("activeProfiles/activeProfile")]
    cases.append(
        check(
            "settings_active_profiles",
            "Parse settings.xml <activeProfiles> activating 'test' profile without CLI -P flag",
            ["test"],
            active_ids,
        )
    )

    # Case 4: Property (-Denv=test) & OS (<activation><os>) matching
    prop_xml = """
    <profile>
      <id>test</id>
      <activation>
        <property><name>env</name><value>test</value></property>
      </activation>
    </profile>
    """
    os_xml = """
    <profile>
      <id>test</id>
      <activation>
        <os><name>Windows XP</name><family>Windows</family><arch>x86</arch><version>5.1.2600</version></os>
      </activation>
    </profile>
    """
    pr = ET.fromstring(prop_xml).find("activation/property")
    cli_props = {"env": "test"}
    prop_matched = cli_props.get(pr.findtext("name")) == pr.findtext("value")

    os_el = ET.fromstring(os_xml).find("activation/os")
    expected_os = {child.tag: child.text.strip() for child in os_el}
    host_xp = {"name": "Windows XP", "family": "Windows", "arch": "x86", "version": "5.1.2600"}
    host_linux = {"name": "Linux", "family": "unix", "arch": "amd64", "version": "6.1"}
    cases.append(
        check(
            "property_and_os_activation",
            "Evaluate -Denv=test property activation and <os> descriptor match vs mismatch",
            {"prop_matched": True, "xp_matched": True, "linux_matched": False},
            {
                "prop_matched": prop_matched,
                "xp_matched": all(host_xp.get(k) == v for k, v in expected_os.items()),
                "linux_matched": all(host_linux.get(k) == v for k, v in expected_os.items()),
            },
        )
    )

    # Case 5: File <missing> / <exists> activation tested on real temp directory
    file_xml = """
    <profile>
      <id>test</id>
      <activation>
        <file>
          <missing>target/generated-sources/axistools/wsdl2java/com/companyname/group</missing>
        </file>
      </activation>
    </profile>
    """
    missing_rel = ET.fromstring(file_xml).findtext("activation/file/missing").strip()
    with tempfile.TemporaryDirectory() as tmp:
        base = Path(tmp)
        target_path = base / missing_rel
        active_before = not target_path.exists()
        target_path.mkdir(parents=True, exist_ok=True)
        active_after = not target_path.exists()
    cases.append(
        check(
            "file_missing_and_exists_activation",
            "Verify <activation><file><missing> activates when path is absent and deactivates once created",
            {"active_when_missing": True, "active_after_created": False},
            {"active_when_missing": active_before, "active_after_created": active_after},
        )
    )

    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-build-profiles-lab/explore-build-profiles.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-build-profiles.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Maven

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2178.zip

下载课程关联工程包:Maven

课程关联工程包(登记关联25章) · 含当前章节或实例 · mbskycom202612a2175.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习