Project

General

Profile

Feature #5778 ยป httpresponse.patch

regularfry (Alex Young), 12/20/2011 02:02 AM

View differences:

lib/webrick/httpresponse.rb
24 24
    attr_accessor :reason_phrase
25 25

  
26 26
    ##
27
    # Body may be a String or IO subclass.
27
    # Body may be a String or IO subclass, or anything which
28
    # implements #read and #close methods to mimic an IO.  If body
29
    # implements a #bytesize method, that will be used to determine
30
    # the Content-Length header.
28 31

  
29 32
    attr_accessor :body
30 33

  
......
193 196
      elsif %r{^multipart/byteranges} =~ @header['content-type']
194 197
        @header.delete('content-length')
195 198
      elsif @header['content-length'].nil?
196
        unless @body.is_a?(IO)
199
        if @body.respond_to?( :bytesize )
197 200
          @header['content-length'] = @body ? @body.bytesize : 0
198 201
        end
199 202
      end
......
245 248

  
246 249
    def send_body(socket)
247 250
      case @body
248
      when IO then send_body_io(socket)
249
      else send_body_string(socket)
251
      when String then send_body_string(socket)
252
      else send_body_io(socket)
250 253
      end
251 254
    end
252 255

  
test/webrick/test_httpresponse.rb
1 1
require "webrick"
2
require "stringio"
2 3
require "minitest/autorun"
3 4

  
4 5
module WEBrick
......
13 14
      def warn msg
14 15
        @messages << msg
15 16
      end
17

  
18
      def error msg
19
        fail msg
20
      end
21

  
16 22
    end
17 23

  
18 24
    attr_reader :config, :logger, :res
......
45 51

  
46 52
      assert_equal 0, logger.messages.length
47 53
    end
54

  
55

  
56
    def test_can_send_string_response
57
      res.body = "tulips!"
58
      socket = StringIO.new
59
      
60
      res.send_response( socket )
61
      
62
      assert_match /tulips!/, socket.string 
63
    end
64

  
65

  
66
    def test_can_send_io_response
67
      io_r, io_w = IO.pipe
68
      io_w.write "beards!"
69
      io_w.close_write
70
      res.body = io_r
71

  
72
      socket = StringIO.new
73

  
74
      res.send_response( socket )
75
      
76
      assert_match /beards!/, socket.string
77
    end
78

  
79
    
80
    def test_can_send_stringio_response
81
      res.body = StringIO.new("octopodes!")
82
      socket = StringIO.new
83
      
84
      res.send_response( socket )
85

  
86
      assert_match /octopodes!/, socket.string
87
    end
88

  
89

  
90
    def test_can_send_arbitrary_io_like_object
91
      thing = Class.new do
92
        def read(n); @sent = (@sent ? nil : "MIGHTY GIRAFFES"); end
93
        def close; end
94
      end.new
95

  
96
      res.body = thing
97
      socket = StringIO.new
98
      
99
      res.send_response( socket )
100
      
101
      assert_match /MIGHTY GIRAFFES/, socket.string
102
    end
103

  
48 104
  end
49 105
end