CodeSampleX

Exemple

rack-test 2.2.0: Assert Rack::Test::UploadedFile defaults content_type to text/plain rather than inferring MIME types from file extensions and default_host defaults to example.org

Échantillon vérifié pour gem rack-test 2.2.0: Assert Rack::Test::UploadedFile defaults content_type to text/plain rather than inferring MIME types from file…

sha256:a547a5386ea49e912d3240302a7c7194b1828e054d1785eb75c673f73f3711ef

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 rubygems

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
Assert Rack::Test::UploadedFile defaults content_type to text/plain rather than inferring MIME types from file extensions and default_host defaults to example.org
Paquets
Symboles
  • Rack::Test::UploadedFile
  • Rack::Test::UploadedFile#content_type
  • Rack::Test::UploadedFile#original_filename
  • Rack::Test::Session
  • Rack::Test::Session#default_host
  • Rack::Test::Session#post
  • Rack::Test::DEFAULT_HOST
  • Rack::Test::Methods
Environnement
ruby
Créé
2026-08-16T16:44:42Z

Contrat

  1. Rack::Test::UploadedFile.new with an image file path returns 'text/plain' for content_type rather than 'image/png' when the argument is omitted, because UploadedFile defaults content_type to 'text/plain' without inspecting the filename extension.
  2. assert posting an UploadedFile without an explicit content_type sends 'content-type: text/plain' in the multipart body and parses into params with :type 'text/plain'
  3. assert passing an explicit content_type argument overrides the default and preserves 'image/png' in both UploadedFile and multipart params
  4. assert UploadedFile wrapping a StringIO defaults content_type to 'text/plain' when content_type is left unset
  5. assert Rack::Test::Session defaults default_host to 'example.org' rather than 'localhost' when initialized without an explicit host

Fichiers

  • Gemfile
  • Gemfile.lock
  • NOTES.md
  • csx.json
  • src/upload_app.rb
  • test/contract.rb
  • test/fixtures/avatar.png
  • test/fixtures/data.json
  • test/fixtures/document.pdf

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

Code source

Gemfile
# frozen_string_literal: true

source "https://rubygems.org"

gem "rack", "3.2.7"
gem "rack-test", "2.2.0"
gem "minitest", "5.25.4"
Gemfile.lock
GEM
  remote: https://rubygems.org/
  specs:
    minitest (5.25.4)
    rack (3.2.7)
    rack-test (2.2.0)
      rack (>= 1.3)

PLATFORMS
  ruby
  x64-mingw-ucrt
  x86_64-linux
  x86_64-linux-musl

DEPENDENCIES
  minitest (= 5.25.4)
  rack (= 3.2.7)
  rack-test (= 2.2.0)

BUNDLED WITH
   2.6.9
NOTES.md
# Notes on Rack::Test UploadedFile Default Content Type and Session Defaults

## What search_known_solution answered
`search_known_solution` returned no match for `rack-test` default option/argument traps (returning unrelated CLI argument parser samples `sha256:a58f6f21c612813f9bfb5172344901a8e9bacf1f11dea240f82a210daf63bc14` for clap 4 and `sha256:b953db7ef30e702f31dca9192e6ef548a50589157551d3ada4896bd8624d6d8d` for Commander). Another sample (`sha256:cb16ec9117c9887155c2792e1e4607e740fe8c584754b3d6136855be6762490b`) covered Sinatra 4 routing integration with rack-test. This sample isolates and proves default arguments in `Rack::Test::UploadedFile` (`content_type` defaulting to `'text/plain'` rather than inferring from file extension) and `Rack::Test::Session` (`default_host` defaulting to `'example.org'` rather than `localhost`).

## What a model would have written instead
A model constructs `Rack::Test::UploadedFile.new("test/fixtures/avatar.png")` expecting `UploadedFile` to inspect the filename extension and automatically assign `content_type` as `"image/png"`, or expects relative path requests to default to `localhost`.

## How the wrong version fails
Fails at runtime or in endpoint assertions when uploaded files are rejected for having MIME type `"text/plain"` instead of the expected image/binary content type, or when host/cookie matching fails against `"example.org"`.
csx.json
{"case":{"believed":"Rack::Test::UploadedFile automatically infers the MIME content type from the file extension when the content_type argument is omitted.","caseId":"case:sha256:611acb9125dbd943f9b8690aadebc54a88d7b178e9563fd7f583d66989a5b681","contract":["Rack::Test::UploadedFile.new with an image file path returns 'text/plain' for content_type rather than 'image/png' when the argument is omitted, because UploadedFile defaults content_type to 'text/plain' without inspecting the filename extension.","assert posting an UploadedFile without an explicit content_type sends 'content-type: text/plain' in the multipart body and parses into params with :type 'text/plain'","assert passing an explicit content_type argument overrides the default and preserves 'image/png' in both UploadedFile and multipart params","assert UploadedFile wrapping a StringIO defaults content_type to 'text/plain' when content_type is left unset","assert Rack::Test::Session defaults default_host to 'example.org' rather than 'localhost' when initialized without an explicit host"],"goal":"Assert Rack::Test::UploadedFile defaults content_type to text/plain rather than inferring MIME types from file extensions and default_host defaults to example.org","kind":"HOW","packages":["pkg:gem/rack-test@2.2.0","pkg:gem/rack@3.2.7"],"schemaVersion":1,"symbols":["Rack::Test::UploadedFile","Rack::Test::UploadedFile#content_type","Rack::Test::UploadedFile#original_filename","Rack::Test::Session","Rack::Test::Session#default_host","Rack::Test::Session#post","Rack::Test::DEFAULT_HOST","Rack::Test::Methods"]},"contractCommand":["ruby","test/contract.rb"],"environment":{"arch":"x64","ecosystem":"gem","executionContext":"ruby","language":"ruby","os":"linux","packageManager":"rubygems","runtime":"ruby","schemaVersion":1},"license":"MIT-0","packages":["pkg:gem/rack-test@2.2.0","pkg:gem/rack@3.2.7"],"schemaVersion":1,"symbols":["Rack::Test::UploadedFile","Rack::Test::UploadedFile#content_type","Rack::Test::UploadedFile#original_filename","Rack::Test::Session","Rack::Test::Session#default_host","Rack::Test::Session#post","Rack::Test::DEFAULT_HOST","Rack::Test::Methods"],"verifierAdapter":"rubygems@1"}
src/upload_app.rb
# frozen_string_literal: true

require "rack"

# A minimal Rack application that inspects multipart uploads and request environment
class UploadApp
  attr_reader :last_received_params, :last_received_env

  def initialize
    @last_received_params = nil
    @last_received_env = nil
  end

  def call(env)
    @last_received_env = env
    req = Rack::Request.new(env)

    case req.path_info
    when "/upload"
      @last_received_params = req.params
      file_data = req.params["file"] || req.params["avatar"] || req.params["doc"]

      if file_data.is_a?(Hash)
        body = [
          "filename=#{file_data[:filename]}",
          "content_type=#{file_data[:type]}",
          "size=#{file_data[:tempfile]&.size || 0}"
        ].join(";")
        [200, { "content-type" => "text/plain" }, [body]]
      else
        [400, { "content-type" => "text/plain" }, ["missing file payload"]]
      end
    when "/host-info"
      body = "host=#{req.host};port=#{req.port};scheme=#{req.scheme}"
      [200, { "content-type" => "text/plain" }, [body]]
    else
      [404, { "content-type" => "text/plain" }, ["not found"]]
    end
  end
end
test/contract.rb
# frozen_string_literal: true

require "minitest/autorun"
require "rack"
require "rack/test"
require "stringio"
require_relative "../src/upload_app"

class RackTestDefaultsContractTest < Minitest::Test
  include Rack::Test::Methods

  def app
    @app ||= UploadApp.new
  end

  def test_uploaded_file_default_content_type_is_text_plain_regardless_of_extension
    # A naive expectation is that UploadedFile infers MIME type from filename extension
    # (e.g., 'image/png' for .png, 'application/pdf' for .pdf, 'application/json' for .json).
    # In reality, UploadedFile hardcodes content_type = 'text/plain' as default argument.
    png_upload = Rack::Test::UploadedFile.new("test/fixtures/avatar.png")
    assert_equal "text/plain", png_upload.content_type
    refute_equal "image/png", png_upload.content_type
    assert_equal "avatar.png", png_upload.original_filename

    pdf_upload = Rack::Test::UploadedFile.new("test/fixtures/document.pdf")
    assert_equal "text/plain", pdf_upload.content_type
    refute_equal "application/pdf", pdf_upload.content_type
    assert_equal "document.pdf", pdf_upload.original_filename

    json_upload = Rack::Test::UploadedFile.new("test/fixtures/data.json")
    assert_equal "text/plain", json_upload.content_type
    refute_equal "application/json", json_upload.content_type
    assert_equal "data.json", json_upload.original_filename
  end

  def test_multipart_post_transmits_default_text_plain_content_type_to_rack_params
    # When UploadedFile is posted without an explicit content_type, the generated
    # multipart MIME part sets 'content-type: text/plain'.
    # The receiving Rack application parses params['file'][:type] as 'text/plain'.
    upload = Rack::Test::UploadedFile.new("test/fixtures/avatar.png")
    post "/upload", "file" => upload

    assert_equal 200, last_response.status
    assert_includes last_response.body, "filename=avatar.png"
    assert_includes last_response.body, "content_type=text/plain"

    received_file_param = app.last_received_params["file"]
    assert_equal "avatar.png", received_file_param[:filename]
    assert_equal "text/plain", received_file_param[:type]
    refute_equal "image/png", received_file_param[:type]
    assert_kind_of Tempfile, received_file_param[:tempfile]
  end

  def test_explicit_content_type_argument_overrides_default
    # To transmit the correct MIME type, the caller must explicitly pass content_type
    # as the second argument to UploadedFile.new.
    explicit_png = Rack::Test::UploadedFile.new("test/fixtures/avatar.png", "image/png")
    assert_equal "image/png", explicit_png.content_type

    post "/upload", "file" => explicit_png
    assert_equal 200, last_response.status
    assert_includes last_response.body, "content_type=image/png"

    received_file_param = app.last_received_params["file"]
    assert_equal "image/png", received_file_param[:type]
  end

  def test_stringio_uploaded_file_defaults_content_type_to_text_plain
    # When initialized with a StringIO stream, content_type still defaults to 'text/plain'.
    # Note that original_filename is a required keyword argument for StringIO.
    sio = StringIO.new("in-memory binary stream data")
    sio_upload = Rack::Test::UploadedFile.new(sio, original_filename: "in_memory.png")

    assert_equal "text/plain", sio_upload.content_type
    refute_equal "image/png", sio_upload.content_type
    assert_equal "in_memory.png", sio_upload.original_filename

    # Omitting original_filename with StringIO raises ArgumentError
    assert_raises(ArgumentError) do
      Rack::Test::UploadedFile.new(StringIO.new("data"))
    end
  end

  def test_session_default_host_is_example_org_rather_than_localhost
    # When default_host is left unset, Rack::Test defaults to Rack::Test::DEFAULT_HOST ("example.org")
    # rather than "localhost", "127.0.0.1", or "example.com".
    assert_equal "example.org", Rack::Test::DEFAULT_HOST

    session = Rack::Test::Session.new(app)
    assert_equal "example.org", session.default_host
    refute_equal "localhost", session.default_host

    session.get "/host-info"
    assert_equal 200, session.last_response.status
    assert_equal "example.org", session.last_request.host
    assert_equal 80, session.last_request.port
    assert_equal "http", session.last_request.scheme
    assert_equal "example.org", session.last_request.env["SERVER_NAME"]
    assert_equal "80", session.last_request.env["SERVER_PORT"]
  end
end
test/fixtures/avatar.png
MOCK_PNG_IMAGE_BINARY_PAYLOAD
test/fixtures/data.json
{"key": "value", "type": "json_data"}
test/fixtures/document.pdf
%PDF-1.4 mock pdf document payload

Seeder d'origine

csx-seed