サンプル
markupsafe 3.0.3: escape
検証済みサンプル — pypi markupsafe 3.0.3: escape. python 3.12 · linux alpine/x64 · docker で contract を実行し、成功しました: escape() converts &, <, >, ", ' into HTML entities…
sha256:27f3787c1f9c1b5c3ed45f1a92ce51b120454c1a5860c4712f1afae51245c570
このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。
合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。
MIT-0
実行証拠
宣言された環境と署名済みの実行を分けてあります。このサンプルが何をどこで実行したかをそのまま確認できます。
- 証拠の基準
- 署名済みコントラクト合格
- 検証レシート
- 1
- ビルドした署名鍵
- 1
宣言された環境
python linux 24 · ubuntu · glibc 2.39 x64 python python 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 in pkg:pypi/markupsafe@3.0.3
- パッケージ
- シンボル
-
- markupsafe.escape
- 環境
- python
- 作成日
- 2026-08-28T00:01:10Z
コントラクト
- escape() converts &, <, >, ", ' into HTML entities and is idempotent when called on existing Markup instances.
- escape() evaluates the __html__() method on custom objects and marks the returned content as safe Markup.
- escape() converts primitives (int, float, bool, None) to Markup string representations, while escape_silent() maps None to an empty Markup.
- Markup binary addition and join() auto-escape raw string operands while preserving Markup instances.
- Markup.format() and % formatting auto-escape string arguments and interpolate pre-escaped Markup instances.
- Markup.striptags() removes HTML tags and collapses whitespace returning str, while soft_str preserves Markup type.
ファイル
- NOTES.md
- PROMPT.md
- csx.json
- requirements.txt
- spec.json
- src/__init__.py
- src/html_escaper.py
- test/contract.py
ソース
# MarkupSafe HTML Escaping and Markup Handling
## Search and Prior Art
A search using `search_known_solution` for `markupsafe.escape` returned `NO_SAFE_MATCH`. Existing verified samples on the network covered specific niche interactions (`format_map` / bytes encoding and `__html_format__` / `%x` limitations). This sample pins the core HTML escaping semantics, primitive conversion, `__html__` protocol evaluation, concatenation / join auto-escaping, and template formatting in MarkupSafe 3.0.3.
## Pinned Version
- `MarkupSafe==3.0.3` under Python 3.10+
## Observed Behaviour
In MarkupSafe 3.0.3:
1. **HTML Entity Escaping**: `escape()` transforms five special characters (`&`, `<`, `>`, `"`, `'`) into HTML-safe entities (`&`, `<`, `>`, `"`, `'`) and returns a `Markup` string instance.
2. **Idempotency**: Passing an already escaped `Markup` instance to `escape()` returns the instance unchanged without double-escaping.
3. **Primitive Type Conversion**: `escape(None)` converts `None` to `Markup("None")`, whereas `escape_silent(None)` returns an empty `Markup("")`. Numeric and boolean types are converted to their string representations.
4. **`__html__` Protocol**: Any object implementing `__html__()` is recognized by `escape()`, which calls the method and wraps the return value in `Markup`.
5. **Auto-Escaping Operations**: Concatenating a `Markup` instance with plain strings (`Markup + str` or `str + Markup`) automatically escapes the plain string operands. `Markup.join()` escapes plain string elements in an iterable.
6. **Template Formatting and % Interpolation**: `Markup.format()` and `Markup % args` automatically escape plain string arguments while leaving `Markup` instances intact.
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 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
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.
{"case":{"caseId":"case:sha256:7f070efc8683f53a7302e08bc641091b103eef125df7b6cdb559da01d763db42","contract":["escape() converts \u0026, \u003c, \u003e, \", ' into HTML entities and is idempotent when called on existing Markup instances.","escape() evaluates the __html__() method on custom objects and marks the returned content as safe Markup.","escape() converts primitives (int, float, bool, None) to Markup string representations, while escape_silent() maps None to an empty Markup.","Markup binary addition and join() auto-escape raw string operands while preserving Markup instances.","Markup.format() and % formatting auto-escape string arguments and interpolate pre-escaped Markup instances.","Markup.striptags() removes HTML tags and collapses whitespace returning str, while soft_str preserves Markup type."],"goal":"verify markupsafe.escape in pkg:pypi/markupsafe@3.0.3","kind":"HOW","packages":["pkg:pypi/markupsafe@3.0.3"],"schemaVersion":1,"symbols":["markupsafe.escape"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"pypi","executionContext":"python","language":"python","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"pip","runtime":"python","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/markupsafe@3.0.3"],"schemaVersion":1,"subject":"pkg:pypi/markupsafe@3.0.3","symbols":["markupsafe.escape"],"verifierAdapter":"python@1"}
markupsafe==3.0.3
{
"schemaVersion": 1,
"goal": "verify markupsafe.escape in pkg:pypi/markupsafe@3.0.3",
"kind": "HOW",
"packages": [
"pkg:pypi/markupsafe@3.0.3"
],
"symbols": [
"markupsafe.escape"
]
}
"""MarkupSafe HTML escaping utilities."""
from __future__ import annotations
from typing import Any, Iterable
from markupsafe import Markup, escape, escape_silent, soft_str
class SafeFragment:
"""A custom component implementing the __html__ protocol."""
def __init__(self, raw_html: str) -> None:
self._raw_html = raw_html
def __html__(self) -> str:
return self._raw_html
def render_escaped_text(text: Any) -> Markup:
"""Escape text safely into HTML markup."""
return escape(text)
def render_silent(text: Any) -> Markup:
"""Escape text or return empty markup if None."""
return escape_silent(text)
def render_template(template: str, **kwargs: Any) -> Markup:
"""Format a template string with auto-escaped keyword arguments."""
return Markup(template).format(**kwargs)
def join_markup(separator: str, items: Iterable[Any]) -> Markup:
"""Join items with separator, escaping raw strings."""
return Markup(separator).join(items)
"""Contract test proving MarkupSafe 3.0.3 escaping and Markup operations."""
from __future__ import annotations
import sys
from pathlib import Path
# Add workspace root to sys.path
sys.path.insert(0, str(Path(__file__).parent.parent))
from markupsafe import Markup, escape, escape_silent, soft_str
from src.html_escaper import (
SafeFragment,
render_escaped_text,
render_silent,
render_template,
join_markup,
)
def test_escape_html_entities_and_idempotency() -> None:
"""Prove escape() replaces <, >, &, ", ' with HTML entities and is idempotent on Markup."""
raw = '<script>alert("test & demo") && flag(\'val\')</script>'
expected = '<script>alert("test & demo") && flag('val')</script>'
escaped = render_escaped_text(raw)
assert isinstance(escaped, Markup)
assert escaped == expected
# Escaping an existing Markup instance preserves it without double escaping
re_escaped = escape(escaped)
assert isinstance(re_escaped, Markup)
assert re_escaped == expected
def test_escape_primitive_types_and_silent() -> None:
"""Prove escape() converts primitives to strings and escape_silent() handles None."""
assert render_escaped_text(123) == Markup("123")
assert render_escaped_text(3.14) == Markup("3.14")
assert render_escaped_text(True) == Markup("True")
assert render_escaped_text(None) == Markup("None")
# escape_silent returns empty Markup for None, but escapes normal values
assert render_silent(None) == Markup("")
assert render_silent(None) == ""
assert isinstance(render_silent(None), Markup)
assert render_silent("<span>hello</span>") == Markup("<span>hello</span>")
def test_custom_object_html_protocol() -> None:
"""Prove escape() calls __html__() on custom objects and marks content as safe."""
frag = SafeFragment("<strong>Trusted HTML</strong>")
result = render_escaped_text(frag)
assert isinstance(result, Markup)
assert result == Markup("<strong>Trusted HTML</strong>")
def test_concatenation_and_joining() -> None:
"""Prove Markup concatenation and join() auto-escape raw string operands."""
# Addition with Markup auto-escapes string operands from both sides
right_add = Markup("<div>") + "<raw_tag>" + Markup("</div>")
assert right_add == Markup("<div><raw_tag></div>")
assert isinstance(right_add, Markup)
left_add = "<b>" + Markup("safe") + "</b>"
assert left_add == Markup("<b>safe</b>")
assert isinstance(left_add, Markup)
# join_markup auto-escapes plain strings while preserving Markup items
items = ["<untrusted>", Markup("<em>trusted</em>"), "100 < 200"]
joined = join_markup("<hr>", items)
assert joined == Markup("<untrusted><hr><em>trusted</em><hr>100 < 200")
assert isinstance(joined, Markup)
def test_formatting_and_helper() -> None:
"""Prove template formatting and % interpolation auto-escape arguments."""
rendered = render_template(
"<p>User: {user}, Role: {role}</p>",
user="<Alice & Bob>",
role=Markup("<strong>Admin</strong>"),
)
assert rendered == Markup("<p>User: <Alice & Bob>, Role: <strong>Admin</strong></p>")
assert isinstance(rendered, Markup)
# % interpolation
mod_rendered = Markup("Value: %s | Safe: %s") % ("<test>", Markup("<code>code</code>"))
assert mod_rendered == Markup("Value: <test> | Safe: <code>code</code>")
assert isinstance(mod_rendered, Markup)
def test_striptags_and_soft_str() -> None:
"""Prove striptags and soft_str behaviors."""
html_val = Markup("<div class=\"main\">\n <p>Hello <b>World</b>!</p>\n</div>")
assert html_val.striptags() == "Hello World!"
assert type(html_val.striptags()) is str
# soft_str returns Markup if Markup, str if str
m = Markup("<b>hello</b>")
assert soft_str(m) is m
assert isinstance(soft_str(m), Markup)
s = "<b>hello</b>"
assert type(soft_str(s)) is str
def main() -> None:
"""Run all contract tests."""
test_escape_html_entities_and_idempotency()
test_escape_primitive_types_and_silent()
test_custom_object_html_protocol()
test_concatenation_and_joining()
test_formatting_and_helper()
test_striptags_and_soft_str()
print("MarkupSafe contract passed successfully.")
if __name__ == "__main__":
main()
オリジンシーダー
匿名