CodeSampleX

샘플

markupsafe 3.0.3: Verify MarkupSafe 3.0.3 string escaping, idempotency, __html__ protocol handling, and automatic operand escaping in Markup operations.

검증된 샘플 — pypi markupsafe 3.0.3: Verify MarkupSafe 3.0.3 string escaping, idempotency, __html__ protocol handling, and automatic operand escaping in Markup…

sha256:652cdb6d7e7a11385d82d916dea3618038ba21c708d45ec715d9cc5f8cbd041a

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
2
빌드한 서명 키
2
선언된 환경 python linux x64 python python pip

검증 실행 환경

환경 컨트랙트 단계 실행일
python 3.12 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1
2026-08-17
python 3.12 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1
2026-08-18

케이스

HOW
목표
Verify MarkupSafe 3.0.3 string escaping, idempotency, __html__ protocol handling, and automatic operand escaping in Markup operations.
패키지
심벌
  • escape
  • escape_silent
  • Markup
환경
python
생성일
2026-08-17T19:15:22Z

컨트랙트

  1. escape() replaces &, <, >, ", and ' with HTML entities (&amp;, &lt;, &gt;, &#34;, &#39;) and returns a Markup instance that avoids re-escaping when passed to escape() again.
  2. escape() invokes the __html__() method on custom objects and marks the returned content as safe Markup without entity substitution.
  3. Markup.format() and binary concatenation automatically escape raw string arguments while preserving existing Markup instances.
  4. escape_silent() returns an empty Markup string for None while escaping string values identically to escape().
  5. Markup.striptags() removes HTML tags and normalizes consecutive whitespace sequences into single spaces.

파일

  • NOTES.md
  • csx.json
  • requirements.txt
  • test/contract.py

소스 아티팩트 내려받기 (tar.gz)

소스

NOTES.md
# MarkupSafe HTML Escaping and String Formatting Semantics

## Search and Prior Art
A search for known solutions for markupsafe returned sample `sha256:7165aa668a3332e95a7414214c7250c1ba3b40d762ba8657b145704ef6b8c93e`, which verifies Jinja2 `Environment(trim_blocks=True, lstrip_blocks=True)` whitespace control. This sample establishes the standalone contract for the underlying MarkupSafe library.

## Pinned Version
- `MarkupSafe==3.0.3`

## Observed Behaviour
In MarkupSafe 3.0.3, the primary escaping and text formatting behaviours operate as follows:

1. **Character Entity Escaping**: `escape()` replaces five characters with HTML-safe entities: `&` (`&amp;`), `<` (`&lt;`), `>` (`&gt;`), `"` (`&#34;`), and `'` (`&#39;`). It returns a `Markup` string instance.
2. **Idempotency**: Passing an existing `Markup` object back into `escape()` produces an equivalent `Markup` instance without double-escaping entities.
3. **`__html__` Protocol**: Any custom object implementing `__html__()` is recognized by `escape()`, which calls the method and wraps the result as safe `Markup` rather than escaping its markup content.
4. **Automatic Formatting and Concatenation Escaping**:
   - `Markup.format()` automatically escapes raw string arguments, but leaves arguments that are `Markup` instances intact.
   - Binary addition (`+`) with a `Markup` object on the left automatically escapes raw string operands and returns a `Markup` object.
   - `Markup.join()` automatically escapes raw string elements within the iterable.
5. **Null Handling**: `escape_silent(None)` returns an empty `Markup` instance (`Markup('')`), whereas standard `escape(None)` converts `None` to the string `Markup('None')`.
6. **Tag Stripping**: `Markup.striptags()` removes HTML/XML tags and normalizes consecutive whitespace into single spaces.
csx.json
{"case":{"caseId":"case:sha256:1c23a0cf984c49c10f4dd2b6e9e5934cd1addce12c4eee0a52a6bfd11d35a3f8","contract":["escape() replaces \u0026, \u003c, \u003e, \", and ' with HTML entities (\u0026amp;, \u0026lt;, \u0026gt;, \u0026#34;, \u0026#39;) and returns a Markup instance that avoids re-escaping when passed to escape() again.","escape() invokes the __html__() method on custom objects and marks the returned content as safe Markup without entity substitution.","Markup.format() and binary concatenation automatically escape raw string arguments while preserving existing Markup instances.","escape_silent() returns an empty Markup string for None while escaping string values identically to escape().","Markup.striptags() removes HTML tags and normalizes consecutive whitespace sequences into single spaces."],"goal":"Verify MarkupSafe 3.0.3 string escaping, idempotency, __html__ protocol handling, and automatic operand escaping in Markup operations.","kind":"HOW","packages":["pkg:pypi/markupsafe@3.0.3"],"schemaVersion":1,"symbols":["escape","escape_silent","Markup"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","ecosystem":"pypi","executionContext":"python","language":"python","os":"linux","packageManager":"pip","runtime":"python","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/markupsafe@3.0.3"],"schemaVersion":1,"symbols":["escape","escape_silent","Markup"],"verifierAdapter":"python@1"}
requirements.txt
MarkupSafe==3.0.3
test/contract.py
from markupsafe import Markup, escape, escape_silent


class HTMLSnippet:
    def __init__(self, content: str):
        self.content = content

    def __html__(self) -> str:
        return self.content


def test_escape_entities_and_idempotency():
    raw = '<script>alert("1 & 2") && test(\'val\')</script>'
    expected = '&lt;script&gt;alert(&#34;1 &amp; 2&#34;) &amp;&amp; test(&#39;val&#39;)&lt;/script&gt;'
    escaped = escape(raw)

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

    # Idempotency: escaping an existing Markup returns an equal Markup without re-escaping
    re_escaped = escape(escaped)
    assert re_escaped == expected
    assert isinstance(re_escaped, Markup)


def test_custom_object_html_protocol():
    # An object implementing __html__() is marked safe by escape()
    snippet = HTMLSnippet('<strong>custom</strong>')
    result = escape(snippet)
    assert isinstance(result, Markup)
    assert result == '<strong>custom</strong>'


def test_markup_formatting_and_concatenation():
    # Markup.format automatically escapes raw strings but preserves Markup
    template = Markup('<div>Hello, {user}! Role: {role}</div>')
    rendered = template.format(user='<Alice & Bob>', role=Markup('<em>Admin</em>'))
    assert rendered == '<div>Hello, &lt;Alice &amp; Bob&gt;! Role: <em>Admin</em></div>'
    assert isinstance(rendered, Markup)

    # Addition with Markup automatically escapes raw strings
    concatenated = Markup('<p>') + '<test>' + Markup('</p>')
    assert concatenated == '<p>&lt;test&gt;</p>'
    assert isinstance(concatenated, Markup)

    # Markup.join escapes raw strings in iterable
    joined = Markup(', ').join(['<a>', Markup('<b>safe</b>'), '<c>'])
    assert joined == '&lt;a&gt;, <b>safe</b>, &lt;c&gt;'
    assert isinstance(joined, Markup)


def test_escape_silent_behavior():
    # escape_silent returns empty Markup for None, but escapes strings
    assert escape_silent(None) == Markup('')
    assert escape_silent(None) == ''
    assert isinstance(escape_silent(None), Markup)
    assert escape_silent('<tag>') == Markup('&lt;tag&gt;')

    # Standard escape converts None to 'None'
    assert escape(None) == Markup('None')


def test_markup_striptags():
    # Markup.striptags strips HTML tags and normalizes whitespace
    html = Markup('<div>\n  <p>Hello <b>World</b>!</p>\n</div>')
    stripped = html.striptags()
    assert stripped == 'Hello World!'


def main():
    test_escape_entities_and_idempotency()
    test_custom_object_html_protocol()
    test_markup_formatting_and_concatenation()
    test_escape_silent_behavior()
    test_markup_striptags()
    print('Contract passed successfully.')


if __name__ == '__main__':
    main()

오리진 시더

csx-seed