CodeSampleX

Exemplo

markupsafe 3.0.3: Markup

Amostra verificada para pypi markupsafe 3.0.3: Markup. O contrato rodou em python 3.12 · linux alpine/x64 · docker e passou: Markup.striptags() strips all…

sha256:2c92a815130ee851fa9ed799ed5f0d7110e5be86ff6f6734eb5876e8734fb013

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
1
Chaves de assinatura que o compilaram
1
Ambiente declarado linux 24 · ubuntu · glibc 2.39 x64 pip

Ambientes das execuções de verificação

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

Caso

HOW
Objetivo
verify markupsafe.Markup in pkg:pypi/markupsafe@3.0.3
Pacotes
Símbolos
  • markupsafe.Markup
Criado
2026-08-27T23:59:12Z

Contrato

  1. Markup.striptags() strips all HTML tags and comments, normalizes whitespace, unescapes entities, and returns a plain str.
  2. Markup.unescape() decodes HTML/XML entities back into raw text without modifying tags, returning a plain str.
  3. Markup.join() auto-escapes plain string iterable elements while preserving existing Markup instances, returning a Markup instance.
  4. Markup % string formatting auto-escapes plain string values in mappings and tuples while preserving numbers and Markup objects.
  5. Markup operations including repetition (*), slicing, splitting, and casing methods preserve the Markup return type.

Arquivos

  • NOTES.md
  • PROMPT.md
  • csx.json
  • requirements.txt
  • spec.json
  • src/__init__.py
  • src/renderer.py
  • test/contract.py

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

Código-fonte

NOTES.md
# MarkupSafe Markup API: Stripping, Unescaping, Joining, Formatting, and Transformations

## Search Result
- `search_known_solution` returned `NO_SAFE_MATCH` for `markupsafe.Markup` in `pkg:pypi/markupsafe@3.0.3`.
- Existing samples cover `bytes` handling, `format_map()` dynamic mapping, and `__html__` protocol interactions.
- This sample verifies core `markupsafe.Markup` methods: `striptags()`, `unescape()`, `join()`, `%` operator interpolation, and string transformation / type preservation.

## Release Pinned
- `markupsafe==3.0.3` under Python 3.

## Observed Behaviour

1. **`striptags()` Stripping & Whitespace Normalization**:
   - `Markup.striptags()` removes all HTML/XML tags and comments, decodes entity references (`&amp;` to `&`, `&lt;` to `<`), and normalizes consecutive whitespace into single spaces.
   - It returns a plain `str` rather than a `Markup` instance, ensuring stripped content is not accidentally treated as safe HTML.

2. **`unescape()` Entity Decoding**:
   - `Markup.unescape()` decodes HTML entity references back to raw characters while keeping any HTML tags intact.
   - Like `striptags()`, it returns a plain `str`.

3. **`Markup.join()` Auto-Escaping**:
   - When a `Markup` instance is used as a delimiter to join an iterable of strings, any plain `str` item is automatically HTML-escaped.
   - Items that are already `Markup` (or implement `__html__`) are preserved without double escaping, and the return value is a `Markup` instance.

4. **`%` Operator String Formatting**:
   - Applying the `%` operator on a `Markup` format template automatically escapes string values provided in tuples or dictionaries.
   - Non-string values (such as integers or floats) and `Markup` objects are formatted correctly, returning a `Markup` instance.

5. **Type Preservation in String Operations**:
   - Common string operations on `Markup` instances—such as repetition (`*`), slicing (`[start:end]`), splitting (`split()`), case conversion (`upper()`, `lower()`), and trimming (`strip()`)—preserve the `Markup` type.
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.Markup 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.Markup

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:34205ed64b2479e47f7a2e89068dd4d8d19af93ce43946146d80cd3d720cc9b3","contract":["Markup.striptags() strips all HTML tags and comments, normalizes whitespace, unescapes entities, and returns a plain str.","Markup.unescape() decodes HTML/XML entities back into raw text without modifying tags, returning a plain str.","Markup.join() auto-escapes plain string iterable elements while preserving existing Markup instances, returning a Markup instance.","Markup % string formatting auto-escapes plain string values in mappings and tuples while preserving numbers and Markup objects.","Markup operations including repetition (*), slicing, splitting, and casing methods preserve the Markup return type."],"goal":"verify markupsafe.Markup in pkg:pypi/markupsafe@3.0.3","kind":"HOW","packages":["pkg:pypi/markupsafe@3.0.3"],"schemaVersion":1,"symbols":["markupsafe.Markup"]},"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.Markup"],"verifierAdapter":"python@1"}
requirements.txt
markupsafe==3.0.3
spec.json
{
  "schemaVersion": 1,
  "goal": "verify markupsafe.Markup in pkg:pypi/markupsafe@3.0.3",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/markupsafe@3.0.3"
  ],
  "symbols": [
    "markupsafe.Markup"
  ]
}
src/__init__.py
"""MarkupSafe Markup verification package."""
src/renderer.py
"""HTML rendering, sanitization, and join helpers using MarkupSafe."""

from typing import Any, Iterable, Mapping, Union
from markupsafe import Markup


def render_template_mod(
    template: Markup,
    context: Union[tuple, Mapping[str, Any]],
) -> Markup:
    """Format a Markup template string using the % operator with auto-escaping."""
    return template % context


def join_markup_elements(
    separator: Markup,
    items: Iterable[Union[str, Markup]],
) -> Markup:
    """Join an iterable of strings/Markup with a Markup separator, auto-escaping plain strings."""
    return separator.join(items)


def clean_markup_to_text(markup_text: Markup) -> str:
    """Strip all HTML tags and decode HTML entities from markup into plain text."""
    return markup_text.striptags()


def decode_html_entities(markup_text: Markup) -> str:
    """Decode HTML entities in markup back to raw text without stripping tags."""
    return markup_text.unescape()


def repeat_markup(element: Markup, count: int) -> Markup:
    """Repeat a Markup element multiple times preserving Markup type."""
    return element * count
test/contract.py
"""Contract tests proving markupsafe.Markup behavior."""

import os
import sys

# Ensure project root is on sys.path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from markupsafe import Markup
from src.renderer import (
    render_template_mod,
    join_markup_elements,
    clean_markup_to_text,
    decode_html_entities,
    repeat_markup,
)


def test_striptags_behavior():
    """Verify striptags removes tags, collapses whitespace, and unescapes entities."""
    raw = Markup(
        '<!-- header comment -->\n'
        '<div class="container">\n'
        '  <h1>Chapter &amp; Overview</h1>\n'
        '  <p>Text with   &lt;tags&gt;   and <a href="#">links</a>.</p>\n'
        '</div>'
    )
    result = clean_markup_to_text(raw)
    assert isinstance(result, str), f"Expected str, got {type(result)}"
    assert not isinstance(result, Markup), "striptags result should not be a Markup instance"
    assert result == "Chapter & Overview Text with <tags> and links."

    m = Markup("<b>Item 1</b>\n\n  <b>Item 2</b>")
    assert m.striptags() == "Item 1 Item 2"


def test_unescape_behavior():
    """Verify unescape decodes HTML entities while keeping tag structures."""
    raw = Markup('&lt;div class=&quot;box&quot;&gt;Tom &amp; Jerry&#39;s &quot;Show&quot;&lt;/div&gt;')
    result = decode_html_entities(raw)
    assert isinstance(result, str), f"Expected str, got {type(result)}"
    assert not isinstance(result, Markup), "unescape result should not be a Markup instance"
    assert result == '<div class="box">Tom & Jerry\'s "Show"</div>'

    assert Markup("&amp;&lt;&gt;&quot;&#39;").unescape() == "&<>\"'"


def test_join_auto_escaping():
    """Verify Markup.join escapes unescaped strings and preserves Markup."""
    sep = Markup("<br/>")
    items = [
        "<b>raw unescaped</b>",
        Markup("<i>already safe</i>"),
        "A & B < C",
    ]
    joined = join_markup_elements(sep, items)
    assert isinstance(joined, Markup)
    expected = Markup(
        "&lt;b&gt;raw unescaped&lt;/b&gt;<br/>"
        "<i>already safe</i><br/>"
        "A &amp; B &lt; C"
    )
    assert joined == expected

    assert Markup(" | ").join(["<x>", Markup("<y>")]) == Markup("&lt;x&gt; | <y>")


def test_mod_formatting():
    """Verify % formatting auto-escapes string values and preserves Markup / numbers."""
    tmpl_dict = Markup('<div class="%(cls)s"><a href="%(url)s">%(label)s</a> (%(count)d)</div>')
    ctx_dict = {
        "cls": "card <alert>",
        "url": "https://example.com/search?q=1&lang=en",
        "label": Markup("<strong>Safe Label</strong>"),
        "count": 42,
    }
    rendered_dict = render_template_mod(tmpl_dict, ctx_dict)
    assert isinstance(rendered_dict, Markup)
    expected_dict = Markup(
        '<div class="card &lt;alert&gt;">'
        '<a href="https://example.com/search?q=1&amp;lang=en">'
        '<strong>Safe Label</strong></a> (42)</div>'
    )
    assert rendered_dict == expected_dict

    tmpl_tuple = Markup("<span>%s: %.1f%%</span>")
    rendered_tuple = render_template_mod(tmpl_tuple, ("<Header>", 98.6))
    assert isinstance(rendered_tuple, Markup)
    assert rendered_tuple == Markup("<span>&lt;Header&gt;: 98.6%</span>")


def test_type_preservation_and_transformations():
    """Verify Markup type preservation across multiplication, slicing, and string transforms."""
    item = Markup("<li>item</li>")
    repeated = repeat_markup(item, 3)
    assert isinstance(repeated, Markup)
    assert repeated == Markup("<li>item</li><li>item</li><li>item</li>")

    sliced = item[4:8]
    assert isinstance(sliced, Markup)
    assert sliced == Markup("item")

    parts = Markup("<b>a</b> <b>b</b>").split(" ")
    assert len(parts) == 2
    assert all(isinstance(p, Markup) for p in parts)
    assert parts == [Markup("<b>a</b>"), Markup("<b>b</b>")]

    upper_markup = Markup("<em>test</em>").upper()
    assert isinstance(upper_markup, Markup)
    assert upper_markup == Markup("<EM>TEST</EM>")

    stripped = Markup("  <b>safe</b> \n").strip()
    assert isinstance(stripped, Markup)
    assert stripped == Markup("<b>safe</b>")


def main():
    test_striptags_behavior()
    test_unescape_behavior()
    test_join_auto_escaping()
    test_mod_formatting()
    test_type_preservation_and_transformations()
    print("Contract PASS: markupsafe.Markup contract verified successfully.")


if __name__ == "__main__":
    main()

Seeder de origem

anônimo