CodeSampleX

Пример

six 1.17.0: six.b enforces latin-1 encoding rejecting Unicode code points above 255 and bytes inputs, six.u leaves bytes uncoerced, six.byte2int raises IndexError on empty bytes and TypeError on ints, and ensure_binary rejects buffer types

Проверенный пример — pypi six 1.17.0: six.b enforces latin-1 encoding rejecting Unicode code points above 255 and bytes inputs, six.u leaves bytes uncoerced…

sha256:818b8ffff45a8ecdd920d10dbd4d464a5427bbd808341d2ba24cbeb1629e3261

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

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
3
Ключи подписи, собравшие его
3
Заявленная среда 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
python 3.12 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1python:3.12-slim@sha256:09f7da3bc104…
2026-09-08

Кейс

HOW
Цель
six.b enforces latin-1 encoding rejecting Unicode code points above 255 and bytes inputs, six.u leaves bytes uncoerced, six.byte2int raises IndexError on empty bytes and TypeError on ints, and ensure_binary rejects buffer types
Пакеты
Символы
  • six.b
  • six.u
  • six.byte2int
  • six.indexbytes
  • six.iterbytes
  • six.ensure_binary
  • six.ensure_text
  • six.get_function_defaults
  • six.get_function_closure
  • six.create_unbound_method
Окружение
python
Создан
2026-08-17T07:06:57Z

Контракт

  1. six.b strictly encodes strings using latin-1 raising UnicodeEncodeError on code points above 255 and AttributeError on existing bytes rather than coercing via UTF-8 or acting idempotently
  2. six.u is an identity function on Python 3 that returns bytes unchanged without text coercion
  3. six.byte2int is mapped to itemgetter(0) which raises IndexError on empty bytes, raises TypeError on integers, and returns single-character strings when passed str
  4. six.indexbytes raises IndexError on empty byte sequences while supporting negative indexing on populated byte sequences
  5. six.ensure_binary and six.ensure_text strictly reject non-str non-bytes buffer types such as bytearray, memoryview, and None with TypeError
  6. six.get_function_defaults and six.get_function_closure return None rather than empty tuples when defaults or closures are absent
  7. six.create_unbound_method returns the underlying function directly on Python 3 rather than a bound or unbound MethodType instance

Файлы

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

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

Исходный код

NOTES.md
# six Input-Domain Edge Behaviors, Byte Coercion Constraints, and Function Introspection Invariants

## Prior Solutions Found
`search_known_solution` returned several existing samples targeting `six`:
- `sha256:732e90a7812bb3832d77220772ca4ecf7f54a382435cf353ca3d72124d26705a` (covering `six.int2byte` `struct.error`, `six.remove_move` `AttributeError`, and `BaseException` enforcement in `reraise`/`raise_from`)
- `sha256:f69b497db3846754695cca9237722c0e1917a0b5681d8e61f3dc1ae01fb618a8` (covering meta_path import boundaries, dynamic add_move registration limits, MovedAttribute vs MovedModule syntax, and with_metaclass base shedding)
- `sha256:78990b35868b7607dc97d6379eebb760365d86484a54b1113dc0b5f9493c2fe8` (covering find_spec resolution, urllib.parse proxy isolation, and ensure_str type strictness)
- `sha256:3f5b3f83d94682fbde8351b4a098349afeb61dd401909fec162335a871821920` (covering exception instance requirements in `six.reraise` and context suppression in `six.raise_from`)
- `sha256:1d589cd1a4e3e7345c56099fda0c53de453dce837e4355fcbf3b74ea41467f29` (covering PEP 451 import hooks on `_SixMetaPathImporter`)
- `sha256:b96f8ae4a5c194c87f07627a97c4a1d32774c312233f999a3e5677e592faa936` (covering with_metaclass base shedding and add_metaclass `__prepare__` bypass)

This sample addresses distinct input-domain edge behaviors: `six.b` Latin-1 encoding constraints and failure on existing `bytes`, `six.u` non-coercion identity behavior on `bytes`, `six.byte2int` index and type error traps across empty byte sequences and integers, buffer protocol rejection in `six.ensure_binary` and `six.ensure_text`, absent defaults and closure handling in function introspection helpers, and unbound method semantics.

## Pinned Release
- Package: `six`
- Version: `1.17.0` (pinned in `requirements.txt`)

## Observed Behaviour

1. **`six.b` Latin-1 Encoding and Non-Idempotence**:
   On Python 3, `six.b(s)` is defined as `s.encode("latin-1")`.
   - Any character beyond code point 255 (such as `\u0100`, `\u20ac`, or emoji `\U0001f600`) raises `UnicodeEncodeError`. It does not fall back to UTF-8 encoding.
   - Passing an already-encoded `bytes` object (e.g. `six.b(b"hello")` or `six.b(b"")`) raises `AttributeError: 'bytes' object has no attribute 'encode'` instead of returning the byte string idempotently.

2. **`six.u` Identity Behavior**:
   On Python 3, `six.u(s)` is an identity function (`lambda s: s`). Passing a `bytes` object `six.u(b"data")` returns the `bytes` instance unmodified without decoding or raising; `isinstance(six.u(b"data"), six.text_type)` evaluates to `False`.

3. **`six.byte2int` and `six.indexbytes` Input Edge Errors**:
   - `six.byte2int` is mapped to `operator.itemgetter(0)`.
   - Passing empty `b""` raises `IndexError: index out of range` (not `ValueError` or returning 0).
   - Passing an integer (e.g. `65` or `0`, which is the result of indexing `bytes` in Python 3) raises `TypeError: 'int' object is not subscriptable`.
   - Passing a string (e.g. `"A"`) returns `"A"` (a single-character `str`), not an integer `65`.
   - `six.indexbytes` is mapped to `operator.getitem`, raising `IndexError` on empty byte sequences `b""` while supporting negative indexing on populated byte sequences (e.g. `indexbytes(b"\x10\x20", -1) == 0x20`).
   - `six.iterbytes` yields `[]` on empty `b""` and integer values `[0, 255]` on `b"\x00\xff"`.

4. **`six.ensure_binary` and `six.ensure_text` Buffer Type Rejection**:
   - Both coercion helpers strictly accept only `bytes` and `str`.
   - Passing other standard buffer types such as `bytearray(b"")`, `bytearray(b"data")`, `memoryview(b"data")`, `None`, or numeric values raises `TypeError: not expecting type '<class '...'>'`.
   - Lone surrogate Unicode characters (e.g. `\ud800`) raise `UnicodeEncodeError` under default strict error handling, but successfully round-trip when given `errors="surrogatepass"`.

5. **Function Introspection Helpers on Absent Values**:
   - `six.get_function_defaults(fn)` returns `None` (not `()` or `{}`) when a function has no default argument values.
   - `six.get_function_closure(fn)` returns `None` (not `()`) when a function has no closure cells.

6. **Unbound Method Semantics**:
   - `six.create_unbound_method(func, cls)` returns `func` directly on Python 3. It is not an instance of `types.MethodType`.

## How the Wrong Expectation Fails
- Calling `six.b(b"data")` under the assumption that `six.b` is idempotent on byte strings fails loudly with `AttributeError`.
- Calling `six.b("\u20ac")` expecting UTF-8 encoding fails loudly with `UnicodeEncodeError`.
- Relying on `six.u(binary_data)` to produce a text string silently leaves the variable as `bytes`, leading to downstream type mismatches.
- Calling `six.byte2int(b"")` on empty buffers fails loudly with `IndexError`. Calling `six.byte2int(x)` where `x` is already an integer byte from Python 3 byte iteration fails loudly with `TypeError`.
- Passing a `bytearray` buffer to `six.ensure_binary` or `six.ensure_text` fails loudly with `TypeError`.
csx.json
{"case":{"believed":"six.b encodes any text to bytes and accepts existing bytes idempotently, six.u coerces bytes to str, and six.byte2int coerces integer inputs while defaulting empty bytes to zero","caseId":"case:sha256:70b2edbc8c18c548b00cc0f8db2f4a7d86637f74c7c93d42b2503d85ffa509fe","contract":["six.b strictly encodes strings using latin-1 raising UnicodeEncodeError on code points above 255 and AttributeError on existing bytes rather than coercing via UTF-8 or acting idempotently","six.u is an identity function on Python 3 that returns bytes unchanged without text coercion","six.byte2int is mapped to itemgetter(0) which raises IndexError on empty bytes, raises TypeError on integers, and returns single-character strings when passed str","six.indexbytes raises IndexError on empty byte sequences while supporting negative indexing on populated byte sequences","six.ensure_binary and six.ensure_text strictly reject non-str non-bytes buffer types such as bytearray, memoryview, and None with TypeError","six.get_function_defaults and six.get_function_closure return None rather than empty tuples when defaults or closures are absent","six.create_unbound_method returns the underlying function directly on Python 3 rather than a bound or unbound MethodType instance"],"goal":"six.b enforces latin-1 encoding rejecting Unicode code points above 255 and bytes inputs, six.u leaves bytes uncoerced, six.byte2int raises IndexError on empty bytes and TypeError on ints, and ensure_binary rejects buffer types","kind":"HOW","packages":["pkg:pypi/six@1.17.0"],"schemaVersion":1,"symbols":["six.b","six.u","six.byte2int","six.indexbytes","six.iterbytes","six.ensure_binary","six.ensure_text","six.get_function_defaults","six.get_function_closure","six.create_unbound_method"]},"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/six@1.17.0"],"schemaVersion":1,"symbols":["six.b","six.u","six.byte2int","six.indexbytes","six.iterbytes","six.ensure_binary","six.ensure_text","six.get_function_defaults","six.get_function_closure","six.create_unbound_method"],"verifierAdapter":"python@1"}
requirements.lock
six==1.17.0
requirements.txt
six==1.17.0
test/__init__.py
# test package
test/contract.py
"""Contract proving input-domain edge behaviors and type invariants in six."""

import types
import six


def test_b_literal_encoding_edges():
    # six.b encodes string literals using latin-1
    assert six.b("hello") == b"hello"
    assert six.b("") == b""
    assert six.b("\x00\x7f\x80\xff") == b"\x00\x7f\x80\xff"

    # Non-latin1 Unicode characters (> 255) raise UnicodeEncodeError
    for ch in ("\u0100", "\u20ac", "\U0001f600"):
        try:
            six.b(ch)
            raise AssertionError("six.b must fail on non-latin1 unicode character: %r" % ch)
        except UnicodeEncodeError:
            pass

    # Passing already-encoded bytes raises AttributeError because six.b calls .encode()
    for raw_bytes in (b"", b"hello", b"\x00\xff"):
        try:
            six.b(raw_bytes)
            raise AssertionError("six.b on bytes must raise AttributeError")
        except AttributeError:
            pass


def test_u_literal_identity_edges():
    # six.u is an identity function on Python 3 (lambda s: s)
    assert six.u("hello") == "hello"
    assert six.u("") == ""

    # six.u does NOT coerce bytes to text; it returns bytes unchanged
    byte_input = b"raw binary data \x00\xff"
    u_result = six.u(byte_input)
    assert u_result is byte_input
    assert isinstance(u_result, bytes)
    assert not isinstance(u_result, six.text_type)


def test_byte2int_and_indexbytes_domain_edges():
    # six.byte2int is mapped to operator.itemgetter(0)
    assert six.byte2int(b"A") == 65
    assert six.byte2int(b"\x00") == 0
    assert six.byte2int(b"\xff") == 255

    # Empty bytes input raises IndexError
    try:
        six.byte2int(b"")
        raise AssertionError("six.byte2int(b'') must raise IndexError")
    except IndexError:
        pass

    # Integer input raises TypeError (itemgetter cannot index int)
    for int_val in (0, 65, 255):
        try:
            six.byte2int(int_val)
            raise AssertionError("six.byte2int(int) must raise TypeError")
        except TypeError:
            pass

    # String input returns single-character str, not integer
    str_result = six.byte2int("A")
    assert str_result == "A"
    assert isinstance(str_result, str)
    assert not isinstance(str_result, int)

    # six.indexbytes is mapped to operator.getitem
    assert six.indexbytes(b"\x10\x20\x30", 0) == 0x10
    assert six.indexbytes(b"\x10\x20\x30", -1) == 0x30
    assert six.indexbytes(b"\x00", 0) == 0

    try:
        six.indexbytes(b"", 0)
        raise AssertionError("six.indexbytes on empty bytes must raise IndexError")
    except IndexError:
        pass

    # six.iterbytes yields ints on Python 3
    assert list(six.iterbytes(b"")) == []
    assert list(six.iterbytes(b"\x00\x7f\xff")) == [0, 127, 255]


def test_ensure_coercion_buffer_rejection():
    # six.ensure_binary and six.ensure_text handle str and bytes conversions
    assert six.ensure_binary("") == b""
    assert six.ensure_binary("text") == b"text"
    assert six.ensure_binary(b"bytes") == b"bytes"

    assert six.ensure_text(b"") == ""
    assert six.ensure_text(b"bytes") == "bytes"
    assert six.ensure_text("text") == "text"

    # Non-str non-bytes buffer types (bytearray, memoryview, None, 0) raise TypeError
    rejected_inputs = (bytearray(b""), bytearray(b"data"), memoryview(b"data"), None, 0)
    for bad_input in rejected_inputs:
        try:
            six.ensure_binary(bad_input)
            raise AssertionError("six.ensure_binary must reject %r" % type(bad_input))
        except TypeError as exc:
            assert "not expecting type" in str(exc)

        try:
            six.ensure_text(bad_input)
            raise AssertionError("six.ensure_text must reject %r" % type(bad_input))
        except TypeError as exc:
            assert "not expecting type" in str(exc)

    # Lone surrogate Unicode code point handling with surrogatepass handler
    surrogate_char = "\ud800"
    try:
        six.ensure_binary(surrogate_char, encoding="utf-8", errors="strict")
        raise AssertionError("ensure_binary on surrogate with strict errors must raise UnicodeEncodeError")
    except UnicodeEncodeError:
        pass

    surrogate_encoded = six.ensure_binary(surrogate_char, encoding="utf-8", errors="surrogatepass")
    assert surrogate_encoded == b"\xed\xa0\x80"
    surrogate_recovered = six.ensure_text(surrogate_encoded, encoding="utf-8", errors="surrogatepass")
    assert surrogate_recovered == surrogate_char


def test_function_introspection_absent_edges():
    # Functions with absent defaults return None
    def fn_without_defaults(a, b):
        return a + b

    assert six.get_function_defaults(fn_without_defaults) is None
    assert six.get_function_closure(fn_without_defaults) is None

    # Functions with defaults return tuple of default values
    def fn_with_defaults(a, b=0, c="", d=None):
        return a

    defaults = six.get_function_defaults(fn_with_defaults)
    assert defaults == (0, "", None)

    # Closures return tuple of cell objects
    def make_multiplier(factor):
        def multiply(val):
            return val * factor
        return multiply

    closure_fn = make_multiplier(10)
    closure_cells = six.get_function_closure(closure_fn)
    assert isinstance(closure_cells, tuple)
    assert len(closure_cells) == 1
    assert closure_cells[0].cell_contents == 10


def test_method_binding_edges():
    def sample_func(self, x):
        return x * 2

    class SampleClass(object):
        pass

    # six.create_unbound_method on Python 3 returns the bare function
    unbound = six.create_unbound_method(sample_func, SampleClass)
    assert unbound is sample_func
    assert not isinstance(unbound, types.MethodType)

    # six.create_bound_method creates a bound MethodType
    instance = SampleClass()
    bound = six.create_bound_method(sample_func, instance)
    assert isinstance(bound, types.MethodType)
    assert bound(5) == 10
    assert six.get_method_self(bound) is instance
    assert six.get_method_function(bound) is sample_func


if __name__ == "__main__":
    test_b_literal_encoding_edges()
    test_u_literal_identity_edges()
    test_byte2int_and_indexbytes_domain_edges()
    test_ensure_coercion_buffer_rejection()
    test_function_introspection_absent_edges()
    test_method_binding_edges()
    print("All six contract assertions passed.")

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

csx-seed