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

运行 MSWC.ContentRotator 权重调度解析、千次抽样分布与 GetAllContent 离线验证

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-contentrotator.py
explore-contentrotator.py165 行
"""Offline Classic ASP Content Rotator (MSWC.ContentRotator) verification lab (IIS ASP absent)."""
import json
from pathlib import Path
import random
import tempfile


class MockContentRotator:
    """Offline model of ASP 3.0 MSWC.ContentRotator reading Content Schedule Files."""

    @staticmethod
    def parse_schedule(path: Path) -> list[tuple[int, str]]:
        entries: list[tuple[int, str]] = []
        current_weight: int | None = None
        current_lines: list[str] = []

        for raw in path.read_text(encoding="utf-8").splitlines():
            stripped = raw.strip()
            if stripped.startswith("%%"):
                if current_weight is not None:
                    entries.append((current_weight, "\n".join(current_lines).strip()))
                rest = stripped[2:].strip()
                # Strip optional // comment after header
                if "//" in rest:
                    rest = rest.split("//", 1)[0].strip()
                weight = 1
                if rest.startswith("#"):
                    token = rest[1:].split()[0]
                    weight = int(token)
                current_weight = weight
                current_lines = []
            elif current_weight is not None:
                current_lines.append(raw)

        if current_weight is not None:
            entries.append((current_weight, "\n".join(current_lines).strip()))
        return entries

    def ChooseContent(self, path: Path, rng: random.Random) -> str:
        entries = self.parse_schedule(path)
        weights = [w for w, _ in entries]
        snippets = [s for _, s in entries]
        return rng.choices(snippets, weights=weights, k=1)[0]

    def GetAllContent(self, path: Path) -> str:
        entries = self.parse_schedule(path)
        return "<hr>".join(s for _, s in entries)


TEXTADS_SAMPLE = """%% #3
<h2>This is a great day!!</h2>
%% #3
<img src="smiley.gif">
%% #4
<a href="https://example.com">Visit Example Portal</a>
"""

DEFAULT_WEIGHT_SAMPLE = """%% // optional comment without explicit weight
<p>Default weight item</p>
%% #2 // double weight item
<p>Weighted item</p>
"""


def main() -> None:
    cases = []

    with tempfile.TemporaryDirectory(prefix="asp_contentrotator_") as tmp:
        text_dir = Path(tmp) / "text"
        text_dir.mkdir()
        schedule_file = text_dir / "textads.txt"
        schedule_file.write_text(TEXTADS_SAMPLE, encoding="utf-8")

        cr = MockContentRotator()

        # Case 1: Schedule parsing and weight probability ratios (3/10, 3/10, 4/10)
        parsed = cr.parse_schedule(schedule_file)
        total_w = sum(w for w, _ in parsed)
        ratios = [round(w / total_w, 2) for w, _ in parsed]
        expected1 = {
            "entry_count": 3,
            "total_weight": 10,
            "ratios": [0.3, 0.3, 0.4],
        }
        actual1 = {
            "entry_count": len(parsed),
            "total_weight": total_w,
            "ratios": ratios,
        }
        cases.append({
            "name": "contentrotator_schedule_parse_weights",
            "summary": "Verify %% #weight parsing yields 3 HTML snippets with 3/10, 3/10, 4/10 probabilities.",
            "expected": expected1,
            "actual": actual1,
            "passed": actual1 == expected1,
        })

        # Case 2: ChooseContent seeded weighted distribution
        rng = random.Random(2026)
        counts = {s: 0 for _, s in parsed}
        for _ in range(1000):
            picked = cr.ChooseContent(schedule_file, rng)
            counts[picked] += 1
        c_list = [counts[s] for _, s in parsed]
        expected2 = {
            "total_draws": 1000,
            "first_near_300": True,
            "second_near_300": True,
            "third_near_400": True,
        }
        actual2 = {
            "total_draws": sum(c_list),
            "first_near_300": abs(c_list[0] - 300) <= 45,
            "second_near_300": abs(c_list[1] - 300) <= 45,
            "third_near_400": abs(c_list[2] - 400) <= 45,
        }
        cases.append({
            "name": "contentrotator_choose_content_distribution",
            "summary": "Verify ChooseContent selects snippets proportionally to #3/#3/#4 weights across 1000 draws.",
            "expected": expected2,
            "actual": actual2,
            "passed": actual2 == expected2,
        })

        # Case 3: GetAllContent returns every snippet separated by <hr>
        all_html = cr.GetAllContent(schedule_file)
        expected3 = (
            '<h2>This is a great day!!</h2><hr>'
            '<img src="smiley.gif"><hr>'
            '<a href="https://example.com">Visit Example Portal</a>'
        )
        cases.append({
            "name": "contentrotator_get_all_content",
            "summary": "Verify GetAllContent outputs all 3 scheduled HTML strings in order separated by <hr>.",
            "expected": expected3,
            "actual": all_html,
            "passed": all_html == expected3,
        })

        # Case 4: Optional #weight defaults to 1 and // comments are ignored
        default_file = text_dir / "default.txt"
        default_file.write_text(DEFAULT_WEIGHT_SAMPLE, encoding="utf-8")
        def_parsed = cr.parse_schedule(default_file)
        expected4 = [
            [1, "<p>Default weight item</p>"],
            [2, "<p>Weighted item</p>"],
        ]
        actual4 = [[w, s] for w, s in def_parsed]
        cases.append({
            "name": "contentrotator_default_weight_and_comments",
            "summary": "Verify omitted #weight defaults to 1 and // inline header comments are stripped.",
            "expected": expected4,
            "actual": actual4,
            "passed": actual4 == expected4,
        })

    print(json.dumps({
        "version": "CPython 3.12.14 offline Classic ASP / VBScript verifier (IIS ASP absent)",
        "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/asp-contentrotator-lab/explore-contentrotator.py

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

下载课程关联工程包:ASP

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

下载课程关联工程包:ASP

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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