CodeSampleX

Exemple

sorbet-runtime 0.6.13427: Handle T::Enum serialization, deserialization, type contracts, and T::Struct subclassing restrictions in sorbet-runtime

Échantillon vérifié pour gem sorbet-runtime 0.6.13427: Handle T::Enum serialization, deserialization, type contracts, and T::Struct subclassing restrictions…

sha256:e670e1091ab22e46ce68006e734aa4cde0ed100b0682a748df26780705c0d94e

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
2
Clés de signature qui l’ont compilé
2
Environnement déclaré ruby linux x64 ruby ruby bundler

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
ruby 3 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · rubygems@1
2026-08-16
ruby 3 · linux debian/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · rubygems@1
2026-08-18

Cas

HOW
Objectif
Handle T::Enum serialization, deserialization, type contracts, and T::Struct subclassing restrictions in sorbet-runtime
Paquets
Symboles
  • T::Enum
  • T::Struct
  • T::Sig
  • T.nilable
  • T.any
  • T::Configuration
Environnement
ruby
Créé
2026-08-16T17:10:12Z

Contrat

  1. assert T::Enum instances are not equal to strings or symbols, and that passing a raw string to a T::Enum parameter raises TypeError
  2. assert from_serialized raises KeyError on unknown strings rather than returning nil, and try_deserialize is the method that returns nil
  3. assert default serialization converts constant names to lowercase strings rather than preserving constant casing
  4. assert instantiating a T::Enum subclass after initialization raises RuntimeError
  5. assert subclassing a T::Struct raises RuntimeError and constructor rejects unknown keyword arguments with ArgumentError
  6. assert type combinators use T.nilable and T.any because T.optional, T.union, and T.intersection do not exist
  7. assert T::Configuration.call_validation_error_handler can intercept signature failures to prevent raising TypeError

Fichiers

  • Gemfile
  • Gemfile.lock
  • NOTES.md
  • csx.json
  • src/workflow.rb
  • test/contract.rb

Télécharger l’artefact source (tar.gz)

Code source

Gemfile
source "https://rubygems.org"

gem "sorbet-runtime", "0.6.13427"
gem "minitest", "5.25.4"
Gemfile.lock
GEM
  remote: https://rubygems.org/
  specs:
    minitest (5.25.4)
    sorbet-runtime (0.6.13427)

PLATFORMS
  ruby
  x86_64-linux-musl

DEPENDENCIES
  minitest (= 5.25.4)
  sorbet-runtime (= 0.6.13427)

BUNDLED WITH
  2.6.9
NOTES.md
# sorbet-runtime: T::Enum semantics, T::Struct subclassing, and runtime type boundaries

## Prior Knowledge Search
The initial query for `sorbet-runtime` returned a compatible hit:
- `sha256:0e5a23077089e2ffe5fe30132707fc39f81467a95abe8545d6c612eadb7fb18d` ("Know what sorbet-runtime enforces when the static checker is not running, and where the same type expression is checked deeply, shallowly, or not at all").

This sample targets a distinct runtime contract surface: `T::Enum` equality and deserialization mechanics, `T::Struct` inheritance prohibitions, missing type combinators (`T.optional`, `T.union`), and global validation error interception via `T::Configuration`.

## Failure Mode
The naive implementation fails loudly at runtime with `KeyError` when attempting safe lookup via `from_serialized("unknown")` (expecting `nil`), `TypeError` when passing string representations directly into `sig` boundaries expecting `T::Enum`, `RuntimeError` when attempting to subclass `T::Struct` or instantiate `T::Enum` dynamically, and `NoMethodError` when calling TypeScript/Python-inspired combinators like `T.optional`.
csx.json
{"case":{"believed":"T::Enum instances compare equal to their serialized string or symbol values, and from_serialized returns nil for unmatched strings instead of raising KeyError.","caseId":"case:sha256:15100ebcfc7008cbd338b1dda3e7712d6002ca60de0bc157ebd1b8dad56d6bcb","contract":["assert T::Enum instances are not equal to strings or symbols, and that passing a raw string to a T::Enum parameter raises TypeError","assert from_serialized raises KeyError on unknown strings rather than returning nil, and try_deserialize is the method that returns nil","assert default serialization converts constant names to lowercase strings rather than preserving constant casing","assert instantiating a T::Enum subclass after initialization raises RuntimeError","assert subclassing a T::Struct raises RuntimeError and constructor rejects unknown keyword arguments with ArgumentError","assert type combinators use T.nilable and T.any because T.optional, T.union, and T.intersection do not exist","assert T::Configuration.call_validation_error_handler can intercept signature failures to prevent raising TypeError"],"goal":"Handle T::Enum serialization, deserialization, type contracts, and T::Struct subclassing restrictions in sorbet-runtime","kind":"HOW","packages":["pkg:gem/sorbet-runtime@0.6.13427","pkg:gem/minitest@5.25.4"],"schemaVersion":1,"symbols":["T::Enum","T::Struct","T::Sig","T.nilable","T.any","T::Configuration"]},"contractCommand":["ruby","test/contract.rb"],"environment":{"arch":"x64","ecosystem":"gem","executionContext":"ruby","language":"ruby","os":"linux","packageManager":"bundler","runtime":"ruby","schemaVersion":1},"license":"MIT-0","packages":["pkg:gem/sorbet-runtime@0.6.13427","pkg:gem/minitest@5.25.4"],"schemaVersion":1,"symbols":["T::Enum","T::Struct","T::Sig","T.nilable","T.any","T::Configuration"],"verifierAdapter":"rubygems@1"}
src/workflow.rb
# frozen_string_literal: true

require "sorbet-runtime"

module Workflow
  # T::Enum represents fixed enumerated sets.
  # Key runtime characteristics:
  # 1. Enum instances are distinct objects; they do NOT compare equal to Strings or Symbols.
  # 2. Default serialization uses the lowercase string of the constant name.
  # 3. Custom serialized values can be specified via `new("custom_value")`.
  # 4. Deserialization with from_serialized strictly raises KeyError on missing keys.
  # 5. Safe deserialization without raising is provided by try_deserialize.
  # 6. Enum classes cannot be instantiated outside the enums definition block.
  class TaskStatus < T::Enum
    enums do
      Pending = new
      InProgress = new("in_progress")
      Completed = new
    end
  end

  # A domain model demonstrating T::Struct constraints and T::Enum integration.
  # T::Struct instances cannot be subclassed and reject unrecognized keyword arguments.
  class Task < T::Struct
    const :id, Integer
    const :title, String
    prop :status, TaskStatus, default: TaskStatus::Pending
    prop :assignee, T.nilable(String), default: nil
  end

  # A service demonstrating method signatures and error interception.
  class Dispatcher
    extend T::Sig

    sig { params(task: Task, target_status: TaskStatus).returns(TaskStatus) }
    def self.transition(task, target_status)
      task.status = target_status
      target_status
    end

    sig { params(priority: T.any(Integer, String)).returns(String) }
    def self.format_priority(priority)
      "P-#{priority}"
    end
  end
end
test/contract.rb
# frozen_string_literal: true

require "minitest/autorun"
require_relative "../src/workflow"

class WorkflowContractTest < Minitest::Test
  # -------------------------------------------------------------------------
  # 1. T::Enum equality and signature type checking
  # -------------------------------------------------------------------------
  def test_enum_instances_do_not_equal_strings_or_symbols
    status = Workflow::TaskStatus::Pending

    # T::Enum instances are distinct objects, not strings or symbols
    refute_equal "pending", status
    refute_equal "Pending", status
    refute_equal :pending, status
    assert_equal Workflow::TaskStatus::Pending, status
    assert_instance_of Workflow::TaskStatus, status
  end

  def test_signatures_strictly_require_enum_instances_not_serialized_strings
    task = Workflow::Task.new(id: 1, title: "Initial Task")

    # Passing valid enum instance succeeds
    result = Workflow::Dispatcher.transition(task, Workflow::TaskStatus::InProgress)
    assert_equal Workflow::TaskStatus::InProgress, result
    assert_equal Workflow::TaskStatus::InProgress, task.status

    # Passing raw string "in_progress" violates signature and raises TypeError
    err = assert_raises(TypeError) do
      Workflow::Dispatcher.transition(task, "in_progress")
    end
    assert_match(/Expected type Workflow::TaskStatus/, err.message)
    assert_match(/got type String/, err.message)
  end

  # -------------------------------------------------------------------------
  # 2. Deserialization: from_serialized vs try_deserialize
  # -------------------------------------------------------------------------
  def test_from_serialized_raises_key_error_on_unknown_values
    # Valid serialized values deserialize correctly
    assert_equal Workflow::TaskStatus::Pending, Workflow::TaskStatus.from_serialized("pending")
    assert_equal Workflow::TaskStatus::InProgress, Workflow::TaskStatus.from_serialized("in_progress")

    # from_serialized raises KeyError on missing keys (does NOT return nil)
    err = assert_raises(KeyError) do
      Workflow::TaskStatus.from_serialized("archived")
    end
    assert_match(/Enum Workflow::TaskStatus key not found: "archived"/, err.message)

    # Constant casing also fails because default serialization is lowercase
    assert_raises(KeyError) do
      Workflow::TaskStatus.from_serialized("Pending")
    end
  end

  def test_try_deserialize_returns_nil_without_raising
    assert_nil Workflow::TaskStatus.try_deserialize("archived")
    assert_nil Workflow::TaskStatus.try_deserialize("Pending")
    assert_equal Workflow::TaskStatus::Completed, Workflow::TaskStatus.try_deserialize("completed")
  end

  # -------------------------------------------------------------------------
  # 3. Serialization format
  # -------------------------------------------------------------------------
  def test_default_serialization_is_lowercase_string_matching_constant_name
    assert_equal "pending", Workflow::TaskStatus::Pending.serialize
    assert_equal "completed", Workflow::TaskStatus::Completed.serialize
    # Custom serialized value overrides the default
    assert_equal "in_progress", Workflow::TaskStatus::InProgress.serialize
  end

  # -------------------------------------------------------------------------
  # 4. Enum lifecycle: no post-init instantiation
  # -------------------------------------------------------------------------
  def test_instantiating_enum_outside_definition_block_raises_runtime_error
    err = assert_raises(RuntimeError) do
      Workflow::TaskStatus.new
    end
    assert_match(/Cannot instantiate a new enum value of Workflow::TaskStatus/, err.message)
  end

  # -------------------------------------------------------------------------
  # 5. T::Struct restrictions: subclassing and unrecognized keyword args
  # -------------------------------------------------------------------------
  def test_subclassing_a_t_struct_is_forbidden
    err = assert_raises(RuntimeError) do
      Class.new(Workflow::Task) do
        const :deadline, String
      end
    end
    assert_match(/is a subclass of T::Struct and cannot be subclassed/, err.message)
  end

  def test_struct_new_rejects_unrecognized_properties
    err = assert_raises(ArgumentError) do
      Workflow::Task.new(id: 1, title: "Clean Room", extra_field: "unexpected")
    end
    assert_match(/Unrecognized properties: extra_field/, err.message)
  end

  # -------------------------------------------------------------------------
  # 6. Type combinator names
  # -------------------------------------------------------------------------
  def test_type_combinators_use_nilable_and_any_while_optional_and_union_do_not_exist
    assert_raises(NoMethodError) { T.optional(String) }
    assert_raises(NoMethodError) { T.union(Integer, String) }
    assert_raises(NoMethodError) { T.intersection(Comparable, Enumerable) }

    assert_equal "P-101", Workflow::Dispatcher.format_priority(101)
    assert_equal "P-HIGH", Workflow::Dispatcher.format_priority("HIGH")
  end

  # -------------------------------------------------------------------------
  # 7. Global error handler interception
  # -------------------------------------------------------------------------
  def test_call_validation_error_handler_can_intercept_type_errors
    captured = []
    task = Workflow::Task.new(id: 2, title: "Logged Task")

    begin
      T::Configuration.call_validation_error_handler = ->(signature, opts) {
        captured << { message: opts[:pretty_message], param: opts[:param] }
      }

      # With handler installed, calling with invalid argument executes without raising TypeError
      res = Workflow::Dispatcher.transition(task, "invalid_enum_string")
      assert_equal "invalid_enum_string", res
      # Three validations are intercepted: method parameter, struct setter, and return value
      assert_equal 3, captured.size
      assert_match(/Parameter 'target_status': Expected type Workflow::TaskStatus/, captured[0][:message])
      assert_match(/Can't set Workflow::Task\.status/, captured[1][:message])
      assert_match(/Return value: Expected type Workflow::TaskStatus/, captured[2][:message])
    ensure
      T::Configuration.call_validation_error_handler = nil
    end

    # Once handler is reset, type errors raise again
    assert_raises(TypeError) do
      Workflow::Dispatcher.transition(task, "invalid_enum_string")
    end
  end
end

Seeder d'origine

csx-seed