CodeSampleX

Пример

markupsafe 3.0.3: escape

Проверенный пример — pypi markupsafe 3.0.3: escape. Контракт выполнен на python 3.12 · linux alpine/x64 · docker и пройден: escape() converts &, <, >, ", '…

sha256:27f3787c1f9c1b5c3ed45f1a92ce51b120454c1a5860c4712f1afae51245c570

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. 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

Контракт

  1. escape() converts &, <, >, ", ' into HTML entities and is idempotent when called on existing Markup instances.
  2. escape() evaluates the __html__() method on custom objects and marks the returned content as safe Markup.
  3. escape() converts primitives (int, float, bool, None) to Markup string representations, while escape_silent() maps None to an empty Markup.
  4. Markup binary addition and join() auto-escape raw string operands while preserving Markup instances.
  5. Markup.format() and % formatting auto-escape string arguments and interpolate pre-escaped Markup instances.
  6. 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

Скачать артефакт с исходным кодом (tar.gz)

Исходный код

NOTES.md
# 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 (`&amp;`, `&lt;`, `&gt;`, `&#34;`, `&#39;`) 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.
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 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.
csx.json
{"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"}
requirements.txt
markupsafe==3.0.3
spec.json
{
  "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"
  ]
}
src/__init__.py
"""MarkupSafe HTML escaping utilities."""
src/html_escaper.py
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)
test/contract.py
"""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 = '&lt;script&gt;alert(&#34;test &amp; demo&#34;) &amp;&amp; flag(&#39;val&#39;)&lt;/script&gt;'

    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("&lt;span&gt;hello&lt;/span&gt;")


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>&lt;raw_tag&gt;</div>")
    assert isinstance(right_add, Markup)

    left_add = "<b>" + Markup("safe") + "</b>"
    assert left_add == Markup("&lt;b&gt;safe&lt;/b&gt;")
    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("&lt;untrusted&gt;<hr><em>trusted</em><hr>100 &lt; 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: &lt;Alice &amp; Bob&gt;, 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: &lt;test&gt; | 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()

Исходный сидер

аноним