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 GPLv2+ (GPLv3+ preferred)
7 # Additional work donated by contributors. See http://mongrel.rubyforge.org/attributions.html
8 # for more information.
10 STDIN.sync = STDOUT.sync = STDERR.sync = true # buffering makes debugging hard
12 # FIXME: move curl-dependent tests into t/
13 ENV['NO_PROXY'] ||= ENV['UNICORN_TEST_ADDR'] || '127.0.0.1'
15 # Some tests watch a log file or a pid file to spring up to check state
16 # Can't rely on inotify on non-Linux and logging to a pipe makes things
40 STDERR.reopen("test_stderr.#{$$}.log", "a")
41 STDOUT.reopen("test_stdout.#{$$}.log", "a")
42 STDERR.sync = STDOUT.sync = true
45 File.unlink("test_stderr.#{$$}.log") rescue nil
46 File.unlink("test_stdout.#{$$}.log") rescue nil
52 STDERR.reopen(orig_err)
53 STDOUT.reopen(orig_out)
57 # which(1) exit codes cannot be trusted on some systems
58 # We use UNIX shell utilities in some tests because we don't trust
59 # ourselves to write Ruby 100% correctly :)
61 ex = ENV['PATH'].split(/:/).detect do |x|
64 end or warn "`#{bin}' not found in PATH=#{ENV['PATH']}"
68 # Either takes a string to do a get request against, or a tuple of [URI, HTTP] where
69 # HTTP is some kind of Net::HTTP request object (POST, HEAD, etc.)
76 u = 'http://127.0.0.1:8080/' if u == 'http://0.0.0.0:8080/'
77 res = Net::HTTP.get(URI.parse(u))
80 res = Net::HTTP.new(url.host, url.port).start {|h| h.request(u[1]) }
83 assert res != nil, "Didn't get a response: #{u}"
90 # unused_port provides an unused port on +addr+ usable for TCP that is
91 # guaranteed to be unused across all unicorn builds on that system. It
92 # prevents race conditions by using a lock file other unicorn builds
93 # will see. This is required if you perform several builds in parallel
94 # with a continuous integration system or run tests in parallel via
95 # gmake. This is NOT guaranteed to be race-free if you run other
96 # processes that bind to random ports for testing (but the window
97 # for a race condition is very small). You may also set UNICORN_TEST_ADDR
98 # to override the default test address (127.0.0.1).
99 def unused_port(addr = '127.0.0.1')
105 port = base + rand(32768 - base)
106 while port == Unicorn::Const::DEFAULT_PORT
107 port = base + rand(32768 - base)
110 sock = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0)
111 sock.bind(Socket.pack_sockaddr_in(port, addr))
113 rescue Errno::EADDRINUSE, Errno::EACCES
114 sock.close rescue nil
115 retry if (retries -= 1) >= 0
118 # since we'll end up closing the random port we just got, there's a race
119 # condition could allow the random port we just chose to reselect itself
120 # when running tests in parallel with gmake. Create a lock file while
121 # we have the port here to ensure that does not happen .
122 lock_path = "#{Dir::tmpdir}/unicorn_test.#{addr}:#{port}.lock"
123 File.open(lock_path, File::WRONLY|File::CREAT|File::EXCL, 0600).close
124 at_exit { File.unlink(lock_path) rescue nil }
126 sock.close rescue nil
129 sock.close rescue nil
142 # sometimes the server may not come up right away
143 def retry_hit(uris = [])
144 tries = DEFAULT_TRIES
147 rescue Errno::EINVAL, Errno::ECONNREFUSED => err
156 def assert_shutdown(pid)
157 wait_master_ready("test_stderr.#{pid}.log")
158 Process.kill(:QUIT, pid)
159 pid, status = Process.waitpid2(pid)
160 assert status.success?, "exited successfully"
163 def wait_workers_ready(path, nr_workers)
164 tries = DEFAULT_TRIES
166 while (tries -= 1) > 0
168 lines = File.readlines(path).grep(/worker=\d+ ready/)
169 lines.size == nr_workers and return
174 raise "#{nr_workers} workers never became ready:" \
175 "\n\t#{lines.join("\n\t")}\n"
178 def wait_master_ready(master_log)
179 tries = DEFAULT_TRIES
180 while (tries -= 1) > 0
182 File.readlines(master_log).grep(/master process ready/)[0] and return
187 raise "master process never became ready"
190 def reexec_usr2_quit_test(pid, pid_file)
191 assert File.exist?(pid_file), "pid file OK"
192 assert ! File.exist?("#{pid_file}.oldbin"), "oldbin pid file"
193 Process.kill(:USR2, pid)
194 retry_hit(["http://#{@addr}:#{@port}/"])
195 wait_for_file("#{pid_file}.oldbin")
196 wait_for_file(pid_file)
198 old_pid = File.read("#{pid_file}.oldbin").to_i
199 new_pid = File.read(pid_file).to_i
201 # kill old master process
202 assert_not_equal pid, new_pid
203 assert_equal pid, old_pid
204 Process.kill(:QUIT, old_pid)
205 retry_hit(["http://#{@addr}:#{@port}/"])
206 wait_for_death(old_pid)
207 assert_equal new_pid, File.read(pid_file).to_i
208 retry_hit(["http://#{@addr}:#{@port}/"])
209 Process.kill(:QUIT, new_pid)
212 def reexec_basic_test(pid, pid_file)
213 results = retry_hit(["http://#{@addr}:#{@port}/"])
214 assert_equal String, results[0].class
216 master_log = "#{@tmpdir}/test_stderr.#{pid}.log"
217 wait_master_ready(master_log)
218 File.truncate(master_log, 0)
222 hit(["http://#{@addr}:#{@port}/#{i}"])
223 i == kill_point and Process.kill(:HUP, pid)
225 wait_master_ready(master_log)
226 assert File.exist?(pid_file), "pid=#{pid_file} exists"
227 new_pid = File.read(pid_file).to_i
228 assert_not_equal pid, new_pid
229 Process.kill(0, new_pid)
230 Process.kill(:QUIT, new_pid)
233 def wait_for_file(path)
234 tries = DEFAULT_TRIES
235 while (tries -= 1) > 0 && ! File.exist?(path)
238 assert File.exist?(path), "path=#{path} exists #{caller.inspect}"
243 ObjectSpace.each_object(Tempfile) do |tmp|
244 ObjectSpace.undefine_finalizer(tmp)
250 # can't waitpid on detached processes
251 def wait_for_death(pid)
252 tries = DEFAULT_TRIES
253 while (tries -= 1) > 0
257 Process.waitpid(pid, Process::WNOHANG)
265 raise "PID:#{pid} never died!"
268 # executes +cmd+ and chunks its STDOUT
269 def chunked_spawn(stdout, *cmd)
274 crd.sync = cwr.sync = true
284 buf = crd.readpartial(16384)
285 stdout.write("#{'%x' % buf.size}\r\n#{buf}")
287 stdout.write("0\r\n")
288 pid, status = Process.waitpid(pid)
289 exit status.exitstatus
294 def reset_sig_handlers
295 sigs = %w(CHLD).concat(Unicorn::HttpServer::QUEUE_SIGS)
296 sigs.each { |sig| trap(sig, "DEFAULT") }