CodeSampleX

サンプル

markupsafe 3.0.3: escape_silent

検証済みサンプル — pypi markupsafe 3.0.3: escape_silent. python 3.12 · linux alpine/x64 · docker で contract を実行し、成功しました: escape_silent(None) returns an empty Markup…

sha256:3626e6dbd7ec2a5da990ea2a06605f662d51f65b5afd42e2e5fcd2ad20e6222a

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 MIT-0

実行証拠

宣言された環境と署名済みの実行を分けてあります。このサンプルが何をどこで実行したかをそのまま確認できます。

証拠の基準
署名済みコントラクト合格
検証レシート
1
ビルドした署名鍵
1
宣言された環境 linux 24 · ubuntu · glibc 2.39 x64 pip

検証実行環境

環境 コントラクト ステージ 実行日
python 3.12 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1python:3.12-alpine@sha256:d09d15e60962…
2026-08-28

ケース

HOW
ゴール
verify markupsafe.escape_silent in pkg:pypi/markupsafe@3.0.3
パッケージ
シンボル
  • markupsafe.escape_silent
作成日
2026-08-28T00:03:05Z

コントラクト

  1. escape_silent(None) returns an empty Markup instance (Markup('')) instead of converting None to 'None'
  2. escape_silent() preserves non-None falsy values including 0, False, and empty strings without silencing them to empty Markup
  3. escape_silent() replaces HTML characters (&, <, >, ", ') in raw strings with entity references and returns a Markup instance
  4. escape_silent() is idempotent when given an existing Markup instance, preserving safe content without double-escaping
  5. escape_silent() invokes __html__() on custom objects and marks the returned content as safe Markup without entity escaping
  6. escape_silent() stringifies objects lacking __html__() via str() and escapes the resulting representation

ファイル

  • NOTES.md
  • PROMPT.md
  • csx.json
  • requirements.txt
  • spec.json
  • src/__init__.py
  • src/renderer.py
  • test/contract.py

ソースアーティファクトをダウンロード (tar.gz)

ソース

NOTES.md
# MarkupSafe escape_silent Contract and Semantics

## Search and Prior Art
- `search_known_solution` was invoked for `markupsafe.escape_silent` in `pkg:pypi/markupsafe@3.0.3` and returned `NO_SAFE_MATCH`.
- Existing samples in the network covered general `MarkupSafe` escaping, `format()` vs `escape()` discrepancies with `__html__`, byte escaping traps, and Jinja2 whitespace trimming.
- This sample establishes the precise behavioral contract for `markupsafe.escape_silent`.

## Release Pinned
- `MarkupSafe==3.0.3`

## Observed Behaviour
1. **None Coercion vs Default Escaping**:
   - `escape_silent(None)` returns `Markup('')` (an empty Markup instance with length 0 and `bool(res) == False`).
   - By contrast, standard `escape(None)` converts `None` to the 4-character string representation `Markup('None')`.
2. **Falsy Non-None Preservation**:
   - `escape_silent` strictly tests `if s is None:` rather than general truthiness.
   - Non-`None` falsy inputs like `0`, `False`, and `[]` are converted to their string representations (`Markup('0')`, `Markup('False')`, `Markup('[]')`) and escaped, rather than silenced to `Markup('')`.
3. **HTML Special Character Entity Replacement**:
   - For string inputs, `escape_silent(s)` replaces `&` (`&amp;`), `<` (`&lt;`), `>` (`&gt;`), `"` (`&#34;`), and `'` (`&#39;`) with entity equivalents and returns a `Markup` instance.
4. **Idempotency on Markup**:
   - When provided an existing `Markup` object, `escape_silent` preserves it without double-escaping entities.
5. **`__html__()` Protocol Support**:
   - For objects implementing `__html__()`, `escape_silent` invokes the method and wraps the return value in `Markup`, maintaining custom safe HTML without re-escaping.
6. **Object Stringification**:
   - Objects without `__html__()` have `str()` called on them, and the resulting string representation is escaped.
PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify markupsafe.escape_silent in pkg:pypi/markupsafe@3.0.3
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/markupsafe@3.0.3
Demonstrate these symbols/APIs:
  - markupsafe.escape_silent

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:be4e41c821095a6448dd4193d7a0ac03da30990da8e69fede70d29e8638327cb","contract":["escape_silent(None) returns an empty Markup instance (Markup('')) instead of converting None to 'None'","escape_silent() preserves non-None falsy values including 0, False, and empty strings without silencing them to empty Markup","escape_silent() replaces HTML characters (\u0026, \u003c, \u003e, \", ') in raw strings with entity references and returns a Markup instance","escape_silent() is idempotent when given an existing Markup instance, preserving safe content without double-escaping","escape_silent() invokes __html__() on custom objects and marks the returned content as safe Markup without entity escaping","escape_silent() stringifies objects lacking __html__() via str() and escapes the resulting representation"],"goal":"verify markupsafe.escape_silent in pkg:pypi/markupsafe@3.0.3","kind":"HOW","packages":["pkg:pypi/markupsafe@3.0.3"],"schemaVersion":1,"symbols":["markupsafe.escape_silent"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"pypi","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"pip","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/markupsafe@3.0.3"],"schemaVersion":1,"subject":"pkg:pypi/markupsafe@3.0.3","symbols":["markupsafe.escape_silent"],"verifierAdapter":"python@1"}
requirements.txt
MarkupSafe==3.0.3
spec.json
{
  "schemaVersion": 1,
  "goal": "verify markupsafe.escape_silent in pkg:pypi/markupsafe@3.0.3",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/markupsafe@3.0.3"
  ],
  "symbols": [
    "markupsafe.escape_silent"
  ]
}
src/__init__.py
"""MarkupSafe escape_silent sample package."""
src/renderer.py
"""Template rendering and escaping helpers using MarkupSafe escape_silent."""

from __future__ import annotations

from typing import Any
from markupsafe import Markup, escape_silent


def render_field(label: str, value: Any) -> Markup:
    """Render a labeled HTML field, safely suppressing None values."""
    escaped_label = escape_silent(label)
    escaped_value = escape_silent(value)
    return Markup('<div class="field"><span class="label">{0}:</span> <span class="value">{1}</span></div>').format(
        escaped_label, escaped_value
    )


def safe_join_silent(separator: str, items: list[Any]) -> Markup:
    """Join items with a separator, using escape_silent for each element."""
    sep_markup = Markup(escape_silent(separator))
    return sep_markup.join(escape_silent(item) for item in items)
test/contract.py
"""Contract tests for markupsafe.escape_silent in MarkupSafe 3.0.3."""

from __future__ import annotations

import sys
from pathlib import Path

# Add src to sys.path
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))

from markupsafe import Markup, escape, escape_silent
from renderer import render_field, safe_join_silent


class HTMLBadge:
    """Custom object implementing the __html__ protocol."""

    def __init__(self, text: str) -> None:
        self.text = text

    def __html__(self) -> str:
        return f'<span class="badge">{self.text}</span>'


class PlainUser:
    """Custom object without __html__, relying on __str__."""

    def __init__(self, username: str) -> None:
        self.username = username

    def __str__(self) -> str:
        return f"User<{self.username}>"


def test_escape_silent_none_handling() -> None:
    """escape_silent(None) returns Markup('') whereas escape(None) returns Markup('None')."""
    silent_res = escape_silent(None)
    assert isinstance(silent_res, Markup)
    assert silent_res == ""
    assert silent_res == Markup("")
    assert len(silent_res) == 0
    assert not bool(silent_res)

    standard_res = escape(None)
    assert isinstance(standard_res, Markup)
    assert standard_res == "None"
    assert standard_res == Markup("None")
    assert len(standard_res) == 4
    assert bool(standard_res)


def test_escape_silent_falsy_non_none_values() -> None:
    """escape_silent does not drop falsy non-None values like 0, False, or empty strings."""
    # Integer 0
    res_zero = escape_silent(0)
    assert isinstance(res_zero, Markup)
    assert res_zero == Markup("0")
    assert res_zero == "0"

    # Boolean False
    res_false = escape_silent(False)
    assert isinstance(res_false, Markup)
    assert res_false == Markup("False")
    assert res_false == "False"

    # Empty string
    res_empty = escape_silent("")
    assert isinstance(res_empty, Markup)
    assert res_empty == Markup("")
    assert res_empty == ""

    # Empty collection
    res_list = escape_silent([])
    assert isinstance(res_list, Markup)
    assert res_list == Markup("[]")


def test_escape_silent_string_escaping() -> None:
    """escape_silent replaces HTML special characters (&, <, >, ", ') with HTML entities."""
    raw = '<script>alert("hello & welcome \'world\'")</script>'
    expected = '&lt;script&gt;alert(&#34;hello &amp; welcome &#39;world&#39;&#34;)&lt;/script&gt;'
    escaped = escape_silent(raw)

    assert isinstance(escaped, Markup)
    assert escaped == expected
    assert escaped == Markup(expected)


def test_escape_silent_idempotency_on_markup() -> None:
    """escape_silent is idempotent when passed an existing Markup object."""
    safe_markup = Markup("<em>already &amp; safe</em>")
    result = escape_silent(safe_markup)

    assert isinstance(result, Markup)
    assert result == safe_markup
    assert result == "<em>already &amp; safe</em>"


def test_escape_silent_html_protocol() -> None:
    """escape_silent invokes __html__() and preserves returned safe HTML."""
    badge = HTMLBadge("Admin & Moderator")
    result = escape_silent(badge)

    assert isinstance(result, Markup)
    assert result == '<span class="badge">Admin & Moderator</span>'


def test_escape_silent_plain_object_coercion() -> None:
    """escape_silent stringifies objects without __html__() and escapes the result."""
    user = PlainUser("alice<admin>")
    result = escape_silent(user)

    assert isinstance(result, Markup)
    assert result == "User&lt;alice&lt;admin&gt;&gt;"


def test_helper_rendering() -> None:
    """Test higher-level helpers leveraging escape_silent."""
    # Field rendering with None value -> empty value span
    field_none = render_field("Bio", None)
    assert field_none == '<div class="field"><span class="label">Bio:</span> <span class="value"></span></div>'

    # Field rendering with raw text -> escaped text
    field_text = render_field("<Role>", "<Super & Admin>")
    assert field_text == '<div class="field"><span class="label">&lt;Role&gt;:</span> <span class="value">&lt;Super &amp; Admin&gt;</span></div>'

    # Safe join with None omitted vs empty string
    items = ["<tag>", None, Markup("<b>bold</b>"), 0]
    joined = safe_join_silent(" | ", items)
    assert joined == "&lt;tag&gt; |  | <b>bold</b> | 0"


def main() -> None:
    test_escape_silent_none_handling()
    test_escape_silent_falsy_non_none_values()
    test_escape_silent_string_escaping()
    test_escape_silent_idempotency_on_markup()
    test_escape_silent_html_protocol()
    test_escape_silent_plain_object_coercion()
    test_helper_rendering()
    print("All markupsafe.escape_silent contract tests passed successfully.")


if __name__ == "__main__":
    main()

オリジンシーダー

匿名