add GPLv3 option to the license
[unicorn.git] / test / unit / test_server.rb
blob4d06dd3d3d0e2b7c83b0cb58ff0450b1c22687d9
1 # -*- encoding: binary -*-
3 # Copyright (c) 2005 Zed A. Shaw 
4 # You can redistribute it and/or modify it under the same terms as Ruby 1.8 or
5 # the GPLv3
7 # Additional work donated by contributors.  See http://mongrel.rubyforge.org/attributions.html
8 # for more information.
10 require 'test/test_helper'
12 include Unicorn
14 class TestHandler
16   def call(env)
17     while env['rack.input'].read(4096)
18     end
19     [200, { 'Content-Type' => 'text/plain' }, ['hello!\n']]
20     rescue Unicorn::ClientShutdown, Unicorn::HttpParserError => e
21       $stderr.syswrite("#{e.class}: #{e.message} #{e.backtrace.empty?}\n")
22       raise e
23   end
24 end
27 class WebServerTest < Test::Unit::TestCase
29   def setup
30     @valid_request = "GET / HTTP/1.1\r\nHost: www.zedshaw.com\r\nContent-Type: text/plain\r\n\r\n"
31     @port = unused_port
32     @tester = TestHandler.new
33     redirect_test_io do
34       @server = HttpServer.new(@tester, :listeners => [ "127.0.0.1:#{@port}" ] )
35       @server.start
36     end
37   end
39   def teardown
40     redirect_test_io do
41       wait_workers_ready("test_stderr.#$$.log", 1)
42       File.truncate("test_stderr.#$$.log", 0)
43       @server.stop(false)
44     end
45     reset_sig_handlers
46   end
48   def test_preload_app_config
49     teardown
50     tmp = Tempfile.new('test_preload_app_config')
51     ObjectSpace.undefine_finalizer(tmp)
52     app = lambda { ||
53       tmp.sysseek(0)
54       tmp.truncate(0)
55       tmp.syswrite($$)
56       lambda { |env| [ 200, { 'Content-Type' => 'text/plain' }, [ "#$$\n" ] ] }
57     }
58     redirect_test_io do
59       @server = HttpServer.new(app, :listeners => [ "127.0.0.1:#@port"] )
60       @server.start
61     end
62     results = hit(["http://localhost:#@port/"])
63     worker_pid = results[0].to_i
64     assert worker_pid != 0
65     tmp.sysseek(0)
66     loader_pid = tmp.sysread(4096).to_i
67     assert loader_pid != 0
68     assert_equal worker_pid, loader_pid
69     teardown
71     redirect_test_io do
72       @server = HttpServer.new(app, :listeners => [ "127.0.0.1:#@port"],
73                                :preload_app => true)
74       @server.start
75     end
76     results = hit(["http://localhost:#@port/"])
77     worker_pid = results[0].to_i
78     assert worker_pid != 0
79     tmp.sysseek(0)
80     loader_pid = tmp.sysread(4096).to_i
81     assert_equal $$, loader_pid
82     assert worker_pid != loader_pid
83     ensure
84       tmp.close!
85   end
87   def test_broken_app
88     teardown
89     app = lambda { |env| raise RuntimeError, "hello" }
90     # [200, {}, []] }
91     redirect_test_io do
92       @server = HttpServer.new(app, :listeners => [ "127.0.0.1:#@port"] )
93       @server.start
94     end
95     sock = nil
96     assert_nothing_raised do
97       sock = TCPSocket.new('127.0.0.1', @port)
98       sock.syswrite("GET / HTTP/1.0\r\n\r\n")
99     end
101     assert_match %r{\AHTTP/1.[01] 500\b}, sock.sysread(4096)
102     assert_nothing_raised { sock.close }
103   end
105   def test_simple_server
106     results = hit(["http://localhost:#{@port}/test"])
107     assert_equal 'hello!\n', results[0], "Handler didn't really run"
108   end
110   def test_client_shutdown_writes
111     sock = nil
112     buf = nil
113     bs = 15609315 * rand
114     assert_nothing_raised do
115       sock = TCPSocket.new('127.0.0.1', @port)
116       sock.syswrite("PUT /hello HTTP/1.1\r\n")
117       sock.syswrite("Host: example.com\r\n")
118       sock.syswrite("Transfer-Encoding: chunked\r\n")
119       sock.syswrite("Trailer: X-Foo\r\n")
120       sock.syswrite("\r\n")
121       sock.syswrite("%x\r\n" % [ bs ])
122       sock.syswrite("F" * bs)
123       sock.syswrite("\r\n0\r\nX-")
124       "Foo: bar\r\n\r\n".each_byte do |x|
125         sock.syswrite x.chr
126         sleep 0.05
127       end
128       # we wrote the entire request before shutting down, server should
129       # continue to process our request and never hit EOFError on our sock
130       sock.shutdown(Socket::SHUT_WR)
131       buf = sock.read
132     end
133     assert_equal 'hello!\n', buf.split(/\r\n\r\n/).last
134     next_client = Net::HTTP.get(URI.parse("http://127.0.0.1:#@port/"))
135     assert_equal 'hello!\n', next_client
136     lines = File.readlines("test_stderr.#$$.log")
137     assert lines.grep(/^Unicorn::ClientShutdown: /).empty?
138     assert_nothing_raised { sock.close }
139   end
141   def test_client_shutdown_write_truncates
142     sock = nil
143     buf = nil
144     bs = 15609315 * rand
145     assert_nothing_raised do
146       sock = TCPSocket.new('127.0.0.1', @port)
147       sock.syswrite("PUT /hello HTTP/1.1\r\n")
148       sock.syswrite("Host: example.com\r\n")
149       sock.syswrite("Transfer-Encoding: chunked\r\n")
150       sock.syswrite("Trailer: X-Foo\r\n")
151       sock.syswrite("\r\n")
152       sock.syswrite("%x\r\n" % [ bs ])
153       sock.syswrite("F" * (bs / 2.0))
155       # shutdown prematurely, this will force the server to abort
156       # processing on us even during app dispatch
157       sock.shutdown(Socket::SHUT_WR)
158       IO.select([sock], nil, nil, 60) or raise "Timed out"
159       buf = sock.read
160     end
161     assert_equal "", buf
162     next_client = Net::HTTP.get(URI.parse("http://127.0.0.1:#@port/"))
163     assert_equal 'hello!\n', next_client
164     lines = File.readlines("test_stderr.#$$.log")
165     lines = lines.grep(/^Unicorn::ClientShutdown: bytes_read=\d+/)
166     assert_equal 1, lines.size
167     assert_match %r{\AUnicorn::ClientShutdown: bytes_read=\d+ true$}, lines[0]
168     assert_nothing_raised { sock.close }
169   end
171   def test_client_malformed_body
172     sock = nil
173     bs = 15653984
174     assert_nothing_raised do
175       sock = TCPSocket.new('127.0.0.1', @port)
176       sock.syswrite("PUT /hello HTTP/1.1\r\n")
177       sock.syswrite("Host: example.com\r\n")
178       sock.syswrite("Transfer-Encoding: chunked\r\n")
179       sock.syswrite("Trailer: X-Foo\r\n")
180       sock.syswrite("\r\n")
181       sock.syswrite("%x\r\n" % [ bs ])
182       sock.syswrite("F" * bs)
183     end
184     begin
185       File.open("/dev/urandom", "rb") { |fp| sock.syswrite(fp.sysread(16384)) }
186     rescue
187     end
188     assert_nothing_raised { sock.close }
189     next_client = Net::HTTP.get(URI.parse("http://127.0.0.1:#@port/"))
190     assert_equal 'hello!\n', next_client
191     lines = File.readlines("test_stderr.#$$.log")
192     lines = lines.grep(/^Unicorn::HttpParserError: .* true$/)
193     assert_equal 1, lines.size
194   end
196   def do_test(string, chunk, close_after=nil, shutdown_delay=0)
197     # Do not use instance variables here, because it needs to be thread safe
198     socket = TCPSocket.new("127.0.0.1", @port);
199     request = StringIO.new(string)
200     chunks_out = 0
202     while data = request.read(chunk)
203       chunks_out += socket.write(data)
204       socket.flush
205       sleep 0.2
206       if close_after and chunks_out > close_after
207         socket.close
208         sleep 1
209       end
210     end
211     sleep(shutdown_delay)
212     socket.write(" ") # Some platforms only raise the exception on attempted write
213     socket.flush
214   end
216   def test_trickle_attack
217     do_test(@valid_request, 3)
218   end
220   def test_close_client
221     assert_raises IOError do
222       do_test(@valid_request, 10, 20)
223     end
224   end
226   def test_bad_client
227     redirect_test_io do
228       do_test("GET /test HTTP/BAD", 3)
229     end
230   end
232   def test_logger_set
233     assert_equal @server.logger, Unicorn::HttpRequest::DEFAULTS["rack.logger"]
234   end
236   def test_logger_changed
237     tmp = Logger.new($stdout)
238     @server.logger = tmp
239     assert_equal tmp, Unicorn::HttpRequest::DEFAULTS["rack.logger"]
240   end
242   def test_bad_client_400
243     sock = nil
244     assert_nothing_raised do
245       sock = TCPSocket.new('127.0.0.1', @port)
246       sock.syswrite("GET / HTTP/1.0\r\nHost: foo\rbar\r\n\r\n")
247     end
248     assert_match %r{\AHTTP/1.[01] 400\b}, sock.sysread(4096)
249     assert_nothing_raised { sock.close }
250   end
252   def test_http_0_9
253     sock = nil
254     assert_nothing_raised do
255       sock = TCPSocket.new('127.0.0.1', @port)
256       sock.syswrite("GET /hello\r\n")
257     end
258     assert_match 'hello!\n', sock.sysread(4096)
259     assert_nothing_raised { sock.close }
260   end
262   def test_header_is_too_long
263     redirect_test_io do
264       long = "GET /test HTTP/1.1\r\n" + ("X-Big: stuff\r\n" * 15000) + "\r\n"
265       assert_raises Errno::ECONNRESET, Errno::EPIPE, Errno::ECONNABORTED, Errno::EINVAL, IOError do
266         do_test(long, long.length/2, 10)
267       end
268     end
269   end
271   def test_file_streamed_request
272     body = "a" * (Unicorn::Const::MAX_BODY * 2)
273     long = "PUT /test HTTP/1.1\r\nContent-length: #{body.length}\r\n\r\n" + body
274     do_test(long, Unicorn::Const::CHUNK_SIZE * 2 - 400)
275   end
277   def test_file_streamed_request_bad_body
278     body = "a" * (Unicorn::Const::MAX_BODY * 2)
279     long = "GET /test HTTP/1.1\r\nContent-ength: #{body.length}\r\n\r\n" + body
280     assert_raises(EOFError,Errno::ECONNRESET,Errno::EPIPE,Errno::EINVAL,
281                   Errno::EBADF) {
282       do_test(long, Unicorn::Const::CHUNK_SIZE * 2 - 400)
283     }
284   end
286   def test_listener_names
287     assert_equal [ "127.0.0.1:#@port" ], Unicorn.listener_names
288   end