CodeSampleX

サンプル

six 1.17.0: six.int2byte raises struct.error rather than ValueError on out-of-range integers, six.remove_move raises AttributeError instead of KeyError on missing moves, and six exception helpers strictly enforce BaseException types

検証済みサンプル — pypi six 1.17.0: six.int2byte raises struct.error rather than ValueError on out-of-range integers, six.remove_move raises AttributeError instead…

sha256:732e90a7812bb3832d77220772ca4ecf7f54a382435cf353ca3d72124d26705a

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 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.int2byte raises struct.error rather than ValueError on out-of-range integers, six.remove_move raises AttributeError instead of KeyError on missing moves, and six exception helpers strictly enforce BaseException types
パッケージ
シンボル
  • six.int2byte
  • six.byte2int
  • six.indexbytes
  • six.raise_from
  • six.reraise
  • six.remove_move
  • six.ensure_binary
  • six.ensure_text
  • six.ensure_str
環境
python
作成日
2026-08-17T06:55:15Z

コントラクト

  1. six.int2byte raises struct.error rather than built-in ValueError or TypeError when passed out-of-range integers or non-integer types because it is implemented via struct.Struct.pack in Python 3
  2. six.byte2int raises IndexError on empty byte strings and TypeError on non-subscriptable types via operator.itemgetter
  3. six.indexbytes raises IndexError on out-of-bounds indices and TypeError on non-subscriptables
  4. six.raise_from raises TypeError when cause or target does not derive from BaseException, while setting __cause__ to None and __suppress_context__ to True when cause is None
  5. six.reraise raises TypeError when given an invalid traceback object or when instantiating an uncallable type
  6. six.remove_move raises AttributeError rather than KeyError when attempting to delete an unregistered move
  7. six.ensure_binary, six.ensure_text, and six.ensure_str raise TypeError with exact message formatting when passed unsupported object types

ファイル

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

ソースアーティファクトをダウンロード (tar.gz)

ソース

NOTES.md
# six Exception Types, Error Paths, and Input Validation

## Prior Solutions Found
`search_known_solution` returned three existing samples:
- `sha256:f69b497db3846754695cca9237722c0e1917a0b5681d8e61f3dc1ae01fb618a8` (covering meta_path import boundaries, dynamic add_move registration limits, MovedAttribute vs MovedModule syntax, and with_metaclass base shedding)
- `sha256:b96f8ae4a5c194c87f07627a97c4a1d32774c312233f999a3e5677e592faa936` (covering with_metaclass base shedding and add_metaclass __prepare__ bypass)
- `sha256:78990b35868b7607dc97d6379eebb760365d86484a54b1113dc0b5f9493c2fe8` (covering find_spec resolution, urllib.parse proxy isolation, and ensure_str type strictness)

This sample addresses the error paths, input validation invariants, and exact exception types produced across `six` byte manipulation, exception handling, move management, and coercion helpers.

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

## Observed Behaviour

1. **`six.int2byte` and `struct.error`**: Under Python 3, `int2byte` is defined as `struct.Struct(">B").pack`. Passing out-of-range integers (e.g. `-1` or `256`) or non-integer types (e.g. strings or floats) raises `struct.error`. It does not raise `ValueError` (as Python 2 `chr()` did) or `TypeError`. Because `struct.error` does not inherit from `ValueError` or `TypeError`, error handlers expecting standard built-in exception types fail to intercept the failure.
2. **`six.byte2int` and `six.indexbytes`**: `byte2int` is mapped to `operator.itemgetter(0)`. Passing an empty byte string `b""` raises `IndexError: index out of range`, while non-subscriptable types raise `TypeError`. `indexbytes` is mapped to `operator.getitem`, similarly raising `IndexError` on out-of-bounds indexing.
3. **`six.raise_from` Type Enforcement and Context Suppression**: `six.raise_from(value, from_value)` compiles to `raise value from from_value`. If `from_value` is not an instance or subclass of `BaseException` (and not `None`), Python raises `TypeError: exception causes must derive from BaseException`. If `value` is not an exception, `TypeError: exceptions must derive from BaseException` is raised. Supplying `from_value=None` explicitly sets `__cause__` to `None` and sets `__suppress_context__` to `True`.
4. **`six.reraise` Exception Resolution**: When `value` is `None`, `six.reraise(tp, None)` instantiates `tp()`. If the exception class requires positional arguments, a `TypeError` occurs during instantiation. Supplying a non-traceback object to `tb` raises `TypeError: __traceback__ must be a traceback or None`. When `value` is provided as an exception instance differing from `tp`, Python 3 ignores `tp` and raises `value`.
5. **`six.remove_move` Attribute Deletion**: Attempting to remove an unregistered or non-existent move via `six.remove_move(name)` raises `AttributeError: no such move, ...` rather than `KeyError`. For dynamically added moves that were already accessed, `remove_move` properly purges the attribute from `six.moves.__dict__`.
6. **`six.ensure_*` Type Guards**: `six.ensure_binary`, `six.ensure_text`, and `six.ensure_str` raise `TypeError` with exact message `not expecting type '<class '...'>'` when passed unsupported types (e.g. `bytearray`, integer, list). When passed strings with surrogate code points or byte sequences invalid under strict UTF-8, `UnicodeEncodeError` and `UnicodeDecodeError` are raised respectively.

## How the Wrong Version Fails
Code expecting `six.int2byte` to mirror `chr()` or `bytes([x])` and handling `except (ValueError, TypeError):` crashes loudly with an unhandled `struct.error`. Code expecting `six.remove_move` to operate as a dictionary with `except KeyError:` crashes loudly with an uncaught `AttributeError`.
csx.json
{"case":{"believed":"six.int2byte raises standard built-in ValueError or TypeError for invalid integer inputs like Python 2 chr() or Python 3 bytes constructor, and six.remove_move raises KeyError for nonexistent moves","caseId":"case:sha256:4201363a660c5215b3213f70e04a92e7beaeb90a65e603b9c4b5521c024807e0","contract":["six.int2byte raises struct.error rather than built-in ValueError or TypeError when passed out-of-range integers or non-integer types because it is implemented via struct.Struct.pack in Python 3","six.byte2int raises IndexError on empty byte strings and TypeError on non-subscriptable types via operator.itemgetter","six.indexbytes raises IndexError on out-of-bounds indices and TypeError on non-subscriptables","six.raise_from raises TypeError when cause or target does not derive from BaseException, while setting __cause__ to None and __suppress_context__ to True when cause is None","six.reraise raises TypeError when given an invalid traceback object or when instantiating an uncallable type","six.remove_move raises AttributeError rather than KeyError when attempting to delete an unregistered move","six.ensure_binary, six.ensure_text, and six.ensure_str raise TypeError with exact message formatting when passed unsupported object types"],"goal":"six.int2byte raises struct.error rather than ValueError on out-of-range integers, six.remove_move raises AttributeError instead of KeyError on missing moves, and six exception helpers strictly enforce BaseException types","kind":"HOW","packages":["pkg:pypi/six@1.17.0"],"schemaVersion":1,"symbols":["six.int2byte","six.byte2int","six.indexbytes","six.raise_from","six.reraise","six.remove_move","six.ensure_binary","six.ensure_text","six.ensure_str"]},"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.int2byte","six.byte2int","six.indexbytes","six.raise_from","six.reraise","six.remove_move","six.ensure_binary","six.ensure_text","six.ensure_str"],"verifierAdapter":"python@1"}
requirements.txt
six==1.17.0
test/__init__.py
# test package
test/contract.py
"""Verification contract proving exact exception types and error paths across six utility functions."""

import struct
import sys
import types
import six


def test_int2byte_struct_error_behavior():
    """six.int2byte raises struct.error rather than built-in ValueError or TypeError when passed out-of-range integers or non-integer types."""
    # Valid byte conversions
    assert six.int2byte(0) == b"\x00"
    assert six.int2byte(255) == b"\xff"
    assert six.int2byte(65) == b"A"

    # Out-of-range negative integer raises struct.error, NOT ValueError or TypeError
    try:
        six.int2byte(-1)
        raise AssertionError("six.int2byte(-1) must fail")
    except struct.error as e:
        assert not isinstance(e, ValueError), "struct.error does not inherit from ValueError"
        assert not isinstance(e, TypeError), "struct.error does not inherit from TypeError"
    except (ValueError, TypeError):
        raise AssertionError("six.int2byte should not raise standard ValueError or TypeError")

    # Out-of-range positive integer (>255) raises struct.error
    try:
        six.int2byte(256)
        raise AssertionError("six.int2byte(256) must fail")
    except struct.error as e:
        assert not isinstance(e, ValueError)
        assert not isinstance(e, TypeError)

    # Non-integer types raise struct.error in Python 3 struct packing
    try:
        six.int2byte("invalid_char")
        raise AssertionError("six.int2byte with string must fail")
    except struct.error as e:
        assert not isinstance(e, TypeError)


def test_byte2int_and_indexbytes_errors():
    """six.byte2int raises IndexError on empty byte strings and TypeError on non-subscriptable types via operator.itemgetter."""
    # Valid byte extraction
    assert six.byte2int(b"abc") == 97
    assert six.byte2int(b"\xff") == 255

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

    # Non-subscriptable types raise TypeError
    try:
        six.byte2int(12345)
        raise AssertionError("six.byte2int with int must fail with TypeError")
    except TypeError:
        pass

    # indexbytes error handling
    assert six.indexbytes(b"xyz", 1) == 121
    try:
        six.indexbytes(b"xyz", 10)
        raise AssertionError("six.indexbytes out of bounds must fail with IndexError")
    except IndexError:
        pass


def test_raise_from_invalid_inputs_and_context_suppression():
    """six.raise_from raises TypeError when cause or target does not derive from BaseException, while properly setting context."""
    # 1. Valid exception chaining
    root_cause = RuntimeError("root cause")
    try:
        six.raise_from(ValueError("wrapped error"), root_cause)
        raise AssertionError("six.raise_from must raise the target exception")
    except ValueError as exc:
        assert exc.__cause__ is root_cause
        assert exc.__suppress_context__ is True

    # 2. Explicit None cause suppresses context and sets __cause__ to None
    try:
        six.raise_from(ValueError("suppressed context"), None)
        raise AssertionError("six.raise_from must raise the target exception")
    except ValueError as exc:
        assert exc.__cause__ is None
        assert exc.__suppress_context__ is True

    # 3. Invalid cause type raises TypeError
    try:
        six.raise_from(ValueError("valid error"), "invalid string cause")
        raise AssertionError("six.raise_from with invalid cause must fail with TypeError")
    except TypeError as exc:
        assert "exception causes must derive from BaseException" in str(exc)

    # 4. Invalid target type raises TypeError
    try:
        six.raise_from("not an exception", None)
        raise AssertionError("six.raise_from with invalid target must fail with TypeError")
    except TypeError as exc:
        assert "exceptions must derive from BaseException" in str(exc)


def test_reraise_error_paths():
    """six.reraise raises TypeError when given an invalid traceback object or when instantiating an uncallable type."""
    # 1. Invalid traceback object raises TypeError
    try:
        six.reraise(ValueError, ValueError("sample error"), 12345)
        raise AssertionError("six.reraise with non-traceback must fail with TypeError")
    except TypeError as exc:
        assert "must be a traceback or None" in str(exc)

    # 2. value=None instantiates tp(); if tp requires arguments, TypeError is raised
    class RequiredArgumentError(Exception):
        def __init__(self, mandatory_arg):
            super(RequiredArgumentError, self).__init__(mandatory_arg)

    try:
        six.reraise(RequiredArgumentError, None)
        raise AssertionError("six.reraise with uninstantiable exception class must fail with TypeError")
    except TypeError as exc:
        assert "missing 1 required positional argument" in str(exc)

    # 3. value=None with non-callable type raises TypeError
    try:
        six.reraise(42, None)
        raise AssertionError("six.reraise with non-type must fail with TypeError")
    except TypeError as exc:
        assert "not callable" in str(exc)

    # 4. Instance type takes precedence when value is not None
    try:
        six.reraise(KeyError, ValueError("mismatched type"))
        raise AssertionError("six.reraise must raise the provided exception instance")
    except ValueError as exc:
        assert str(exc) == "mismatched type"
    except KeyError:
        raise AssertionError("six.reraise on Python 3 raises the value instance, not tp")


def test_remove_move_error_behavior():
    """six.remove_move raises AttributeError rather than KeyError when attempting to delete an unregistered move."""
    # 1. Non-existent move raises AttributeError
    try:
        six.remove_move("non_existent_symbol_abc_123")
        raise AssertionError("six.remove_move on missing move must fail with AttributeError")
    except AttributeError as exc:
        assert not isinstance(exc, KeyError)
        assert "no such move, 'non_existent_symbol_abc_123'" in str(exc)

    # 2. Dynamic move lifecycle and removal after descriptor resolution
    six.add_move(six.MovedAttribute("temp_test_pi", "math", "math", "pi", "pi"))
    assert six.moves.temp_test_pi > 3.14  # First access triggers descriptor resolution

    # Class descriptor is now removed, instance dict has the value
    assert "temp_test_pi" not in six._MovedItems.__dict__
    assert "temp_test_pi" in six.moves.__dict__

    # remove_move cleans up instance dict
    six.remove_move("temp_test_pi")
    assert "temp_test_pi" not in six.moves.__dict__

    # Subsequent removal raises AttributeError
    try:
        six.remove_move("temp_test_pi")
        raise AssertionError("Subsequent remove_move must fail with AttributeError")
    except AttributeError:
        pass


def test_ensure_helpers_type_error_paths():
    """six.ensure_binary, six.ensure_text, and six.ensure_str raise TypeError with exact message formatting on unsupported types."""
    # ensure_binary on non-(bytes, str) raises TypeError
    try:
        six.ensure_binary(12345)
        raise AssertionError("six.ensure_binary on int must fail with TypeError")
    except TypeError as exc:
        assert str(exc) == "not expecting type '<class 'int'>'"

    # ensure_text on non-(bytes, str) raises TypeError
    try:
        six.ensure_text([1, 2, 3])
        raise AssertionError("six.ensure_text on list must fail with TypeError")
    except TypeError as exc:
        assert str(exc) == "not expecting type '<class 'list'>'"

    # ensure_str on bytearray raises TypeError (bytearray is not bytes or str)
    try:
        six.ensure_str(bytearray(b"sample"))
        raise AssertionError("six.ensure_str on bytearray must fail with TypeError")
    except TypeError as exc:
        assert str(exc) == "not expecting type '<class 'bytearray'>'"

    # Invalid unicode encoding / decoding errors with strict error handling
    try:
        six.ensure_binary("invalid\ud800surrogate", encoding="utf-8", errors="strict")
        raise AssertionError("six.ensure_binary with surrogate must fail with UnicodeEncodeError")
    except UnicodeEncodeError:
        pass

    try:
        six.ensure_text(b"\xff\xfe", encoding="utf-8", errors="strict")
        raise AssertionError("six.ensure_text with invalid utf-8 must fail with UnicodeDecodeError")
    except UnicodeDecodeError:
        pass


if __name__ == "__main__":
    test_int2byte_struct_error_behavior()
    test_byte2int_and_indexbytes_errors()
    test_raise_from_invalid_inputs_and_context_suppression()
    test_reraise_error_paths()
    test_remove_move_error_behavior()
    test_ensure_helpers_type_error_paths()
    print("Contract verified: all six error paths and exception types verified.")

オリジンシーダー

csx-seed