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.
6 # Additional work donated by contributors. See http://mongrel.rubyforge.org/attributions.html
7 # for more information.
9 STDIN.sync = STDOUT.sync = STDERR.sync = true # buffering makes debugging hard
11 # FIXME: move curl-dependent tests into t/
12 ENV['NO_PROXY'] ||= ENV['UNICORN_TEST_ADDR'] || '127.0.0.1'
14 # Some tests watch a log file or a pid file to spring up to check state
15 # Can't rely on inotify on non-Linux and logging to a pipe makes things
20 HERE = File.dirname(__FILE__) unless defined?(HERE)
21 %w(lib ext).each do |dir|
22 $LOAD_PATH.unshift "#{HERE}/../#{dir}"
35 require 'unicorn_http'
45 STDERR.reopen("test_stderr.#{$$}.log", "a")
46 STDOUT.reopen("test_stdout.#{$$}.log", "a")
47 STDERR.sync = STDOUT.sync = true
50 File.unlink("test_stderr.#{$$}.log") rescue nil
51 File.unlink("test_stdout.#{$$}.log") rescue nil
57 STDERR.reopen(orig_err)
58 STDOUT.reopen(orig_out)
62 # which(1) exit codes cannot be trusted on some systems
63 # We use UNIX shell utilities in some tests because we don't trust
64 # ourselves to write Ruby 100% correctly :)
66 ex = ENV['PATH'].split(/:/).detect do |x|
69 end or warn "`#{bin}' not found in PATH=#{ENV['PATH']}"
73 # Either takes a string to do a get request against, or a tuple of [URI, HTTP] where
74 # HTTP is some kind of Net::HTTP request object (POST, HEAD, etc.)
81 res = Net::HTTP.get(URI.parse(u))
84 res = Net::HTTP.new(url.host, url.port).start {|h| h.request(u[1]) }
87 assert res != nil, "Didn't get a response: #{u}"
94 # unused_port provides an unused port on +addr+ usable for TCP that is
95 # guaranteed to be unused across all unicorn builds on that system. It
96 # prevents race conditions by using a lock file other unicorn builds
97 # will see. This is required if you perform several builds in parallel
98 # with a continuous integration system or run tests in parallel via
99 # gmake. This is NOT guaranteed to be race-free if you run other
100 # processes that bind to random ports for testing (but the window
101 # for a race condition is very small). You may also set UNICORN_TEST_ADDR
102 # to override the default test address (127.0.0.1).
103 def unused_port(addr = '127.0.0.1')
109 port = base + rand(32768 - base)
110 while port == Unicorn::Const::DEFAULT_PORT
111 port = base + rand(32768 - base)
114 sock = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0)
115 sock.bind(Socket.pack_sockaddr_in(port, addr))
117 rescue Errno::EADDRINUSE, Errno::EACCES
118 sock.close rescue nil
119 retry if (retries -= 1) >= 0
122 # since we'll end up closing the random port we just got, there's a race
123 # condition could allow the random port we just chose to reselect itself
124 # when running tests in parallel with gmake. Create a lock file while
125 # we have the port here to ensure that does not happen .
126 lock_path = "#{Dir::tmpdir}/unicorn_test.#{addr}:#{port}.lock"
127 lock = File.open(lock_path, File::WRONLY|File::CREAT|File::EXCL, 0600)
128 at_exit { File.unlink(lock_path) rescue nil }
130 sock.close rescue nil
133 sock.close rescue nil
146 # sometimes the server may not come up right away
147 def retry_hit(uris = [])
148 tries = DEFAULT_TRIES
151 rescue Errno::EINVAL, Errno::ECONNREFUSED => err
160 def assert_shutdown(pid)
161 wait_master_ready("test_stderr.#{pid}.log")
162 assert_nothing_raised { Process.kill(:QUIT, pid) }
164 assert_nothing_raised { pid, status = Process.waitpid2(pid) }
165 assert status.success?, "exited successfully"
168 def wait_workers_ready(path, nr_workers)
169 tries = DEFAULT_TRIES
171 while (tries -= 1) > 0
173 lines = File.readlines(path).grep(/worker=\d+ ready/)
174 lines.size == nr_workers and return
179 raise "#{nr_workers} workers never became ready:" \
180 "\n\t#{lines.join("\n\t")}\n"
183 def wait_master_ready(master_log)
184 tries = DEFAULT_TRIES
185 while (tries -= 1) > 0
187 File.readlines(master_log).grep(/master process ready/)[0] and return
192 raise "master process never became ready"
195 def reexec_usr2_quit_test(pid, pid_file)
196 assert File.exist?(pid_file), "pid file OK"
197 assert ! File.exist?("#{pid_file}.oldbin"), "oldbin pid file"
198 assert_nothing_raised { Process.kill(:USR2, pid) }
199 assert_nothing_raised { retry_hit(["http://#{@addr}:#{@port}/"]) }
200 wait_for_file("#{pid_file}.oldbin")
201 wait_for_file(pid_file)
203 old_pid = File.read("#{pid_file}.oldbin").to_i
204 new_pid = File.read(pid_file).to_i
206 # kill old master process
207 assert_not_equal pid, new_pid
208 assert_equal pid, old_pid
209 assert_nothing_raised { Process.kill(:QUIT, old_pid) }
210 assert_nothing_raised { retry_hit(["http://#{@addr}:#{@port}/"]) }
211 wait_for_death(old_pid)
212 assert_equal new_pid, File.read(pid_file).to_i
213 assert_nothing_raised { retry_hit(["http://#{@addr}:#{@port}/"]) }
214 assert_nothing_raised { Process.kill(:QUIT, new_pid) }
217 def reexec_basic_test(pid, pid_file)
218 results = retry_hit(["http://#{@addr}:#{@port}/"])
219 assert_equal String, results[0].class
220 assert_nothing_raised { Process.kill(0, pid) }
221 master_log = "#{@tmpdir}/test_stderr.#{pid}.log"
222 wait_master_ready(master_log)
223 File.truncate(master_log, 0)
226 assert_nothing_raised do
228 hit(["http://#{@addr}:#{@port}/#{i}"])
229 i == kill_point and Process.kill(:HUP, pid)
232 wait_master_ready(master_log)
233 assert File.exist?(pid_file), "pid=#{pid_file} exists"
234 new_pid = File.read(pid_file).to_i
235 assert_not_equal pid, new_pid
236 assert_nothing_raised { Process.kill(0, new_pid) }
237 assert_nothing_raised { Process.kill(:QUIT, new_pid) }
240 def wait_for_file(path)
241 tries = DEFAULT_TRIES
242 while (tries -= 1) > 0 && ! File.exist?(path)
245 assert File.exist?(path), "path=#{path} exists #{caller.inspect}"
250 ObjectSpace.each_object(Tempfile) do |tmp|
251 ObjectSpace.undefine_finalizer(tmp)
257 # can't waitpid on detached processes
258 def wait_for_death(pid)
259 tries = DEFAULT_TRIES
260 while (tries -= 1) > 0
264 Process.waitpid(pid, Process::WNOHANG)
272 raise "PID:#{pid} never died!"
275 # executes +cmd+ and chunks its STDOUT
276 def chunked_spawn(stdout, *cmd)
281 crd.sync = cwr.sync = true
291 buf = crd.readpartial(16384)
292 stdout.write("#{'%x' % buf.size}\r\n#{buf}")
294 stdout.write("0\r\n")
295 pid, status = Process.waitpid(pid)
296 exit status.exitstatus
301 def reset_sig_handlers
302 sigs = %w(CHLD).concat(Unicorn::HttpServer::QUEUE_SIGS)
303 sigs.each { |sig| trap(sig, "DEFAULT") }