Exemple
markupsafe 3.0.3: escape_silent
Échantillon vérifié pour pypi markupsafe 3.0.3: escape_silent. Le contrat s'est exécuté sur python 3.12 · linux alpine/x64 · docker et a réussi.
sha256:3626e6dbd7ec2a5da990ea2a06605f662d51f65b5afd42e2e5fcd2ad20e6222a
Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré.
Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes.
MIT-0
Preuves d'exécution
L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.
- Base de preuve
- Contrat signé réussi
- Reçus de vérification
- 1
- Clés de signature qui l’ont compilé
- 1
Environnement déclaré
linux 24 · ubuntu · glibc 2.39 x64 pip
Environnements des exécutions de vérification
| Environnement | Contrat | Étapes | Exécution |
|---|---|---|---|
| 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 |
Cas
HOW- Objectif
- verify markupsafe.escape_silent in pkg:pypi/markupsafe@3.0.3
- Paquets
- Symboles
-
- markupsafe.escape_silent
- Créé
- 2026-08-28T00:03:05Z
Contrat
- 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 (&, <, >, ", ') 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
Fichiers
- NOTES.md
- PROMPT.md
- csx.json
- requirements.txt
- spec.json
- src/__init__.py
- src/renderer.py
- test/contract.py
Code source
# 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 `&` (`&`), `<` (`<`), `>` (`>`), `"` (`"`), and `'` (`'`) 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.
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.
{"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"}
MarkupSafe==3.0.3
{
"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"
]
}
"""MarkupSafe escape_silent sample package."""
"""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)
"""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 = '<script>alert("hello & welcome 'world'")</script>'
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 & safe</em>")
result = escape_silent(safe_markup)
assert isinstance(result, Markup)
assert result == safe_markup
assert result == "<em>already & 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<alice<admin>>"
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"><Role>:</span> <span class="value"><Super & Admin></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 == "<tag> | | <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()
Seeder d'origine
anonyme