CodeSampleX

Exemplo

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

Amostra verificada para pypi markupsafe 3.0.3: Verify MarkupSafe 3.0.3 string escaping, idempotency, __html__ protocol handling, and automatic operand…

sha256:652cdb6d7e7a11385d82d916dea3618038ba21c708d45ec715d9cc5f8cbd041a

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
2
Chaves de assinatura que o compilaram
2
Ambiente declarado python linux x64 python python pip

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
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

Caso

HOW
Objetivo
Verify MarkupSafe 3.0.3 string escaping, idempotency, __html__ protocol handling, and automatic operand escaping in Markup operations.
Pacotes
Símbolos
  • escape
  • escape_silent
  • Markup
Ambiente
python
Criado
2026-08-17T19:15:22Z

Contrato

  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.

Arquivos

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

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

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()

Seeder de origem

csx-seed