1 # Copyright (c) 2005 Zed A. Shaw
2 # You can redistribute it and/or modify it under the same terms as Ruby.
4 # Additional work donated by contributors. See http://mongrel.rubyforge.org/attributions.html
5 # for more information.
7 STDIN.sync = STDOUT.sync = STDERR.sync = true # buffering makes debugging hard
9 # Some tests watch a log file or a pid file to spring up to check state
10 # Can't rely on inotify on non-Linux and logging to a pipe makes things
15 HERE = File.dirname(__FILE__) unless defined?(HERE)
16 %w(lib ext).each do |dir|
17 $LOAD_PATH.unshift "#{HERE}/../#{dir}"
30 require 'unicorn/http11'
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 res = Net::HTTP.get(URI.parse(u))
79 res = Net::HTTP.new(url.host, url.port).start {|h| h.request(u[1]) }
82 assert res != nil, "Didn't get a response: #{u}"
89 # unused_port provides an unused port on +addr+ usable for TCP that is
90 # guaranteed to be unused across all unicorn builds on that system. It
91 # prevents race conditions by using a lock file other unicorn builds
92 # will see. This is required if you perform several builds in parallel
93 # with a continuous integration system or run tests in parallel via
94 # gmake. This is NOT guaranteed to be race-free if you run other
95 # processes that bind to random ports for testing (but the window
96 # for a race condition is very small). You may also set UNICORN_TEST_ADDR
97 # to override the default test address (127.0.0.1).
98 def unused_port(addr = '127.0.0.1')
104 port = base + rand(32768 - base)
105 sock = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0)
106 sock.bind(Socket.pack_sockaddr_in(port, addr))
108 rescue Errno::EADDRINUSE, Errno::EACCES
109 sock.close rescue nil
110 retry if (retries -= 1) >= 0
113 # since we'll end up closing the random port we just got, there's a race
114 # condition could allow the random port we just chose to reselect itself
115 # when running tests in parallel with gmake. Create a lock file while
116 # we have the port here to ensure that does not happen .
117 lock_path = "#{Dir::tmpdir}/unicorn_test.#{addr}:#{port}.lock"
118 lock = File.open(lock_path, File::WRONLY|File::CREAT|File::EXCL, 0600)
119 at_exit { File.unlink(lock_path) rescue nil }
121 sock.close rescue nil
124 sock.close rescue nil
137 # sometimes the server may not come up right away
138 def retry_hit(uris = [])
139 tries = DEFAULT_TRIES
142 rescue Errno::ECONNREFUSED => err
151 def assert_shutdown(pid)
152 wait_master_ready("test_stderr.#{pid}.log")
153 assert_nothing_raised { Process.kill(:QUIT, pid) }
155 assert_nothing_raised { pid, status = Process.waitpid2(pid) }
156 assert status.success?, "exited successfully"
159 def wait_workers_ready(path, nr_workers)
160 tries = DEFAULT_TRIES
162 while (tries -= 1) > 0
164 lines = File.readlines(path).grep(/worker=\d+ ready/)
165 lines.size == nr_workers and return
170 raise "#{nr_workers} workers never became ready:" \
171 "\n\t#{lines.join("\n\t")}\n"
174 def wait_master_ready(master_log)
175 tries = DEFAULT_TRIES
176 while (tries -= 1) > 0
178 File.readlines(master_log).grep(/master process ready/)[0] and return
183 raise "master process never became ready"
186 def reexec_usr2_quit_test(pid, pid_file)
187 assert File.exist?(pid_file), "pid file OK"
188 assert ! File.exist?("#{pid_file}.oldbin"), "oldbin pid file"
189 assert_nothing_raised { Process.kill(:USR2, pid) }
190 assert_nothing_raised { retry_hit(["http://#{@addr}:#{@port}/"]) }
191 wait_for_file("#{pid_file}.oldbin")
192 wait_for_file(pid_file)
194 old_pid = File.read("#{pid_file}.oldbin").to_i
195 new_pid = File.read(pid_file).to_i
197 # kill old master process
198 assert_not_equal pid, new_pid
199 assert_equal pid, old_pid
200 assert_nothing_raised { Process.kill(:QUIT, old_pid) }
201 assert_nothing_raised { retry_hit(["http://#{@addr}:#{@port}/"]) }
202 wait_for_death(old_pid)
203 assert_equal new_pid, File.read(pid_file).to_i
204 assert_nothing_raised { retry_hit(["http://#{@addr}:#{@port}/"]) }
205 assert_nothing_raised { Process.kill(:QUIT, new_pid) }
208 def reexec_basic_test(pid, pid_file)
209 results = retry_hit(["http://#{@addr}:#{@port}/"])
210 assert_equal String, results[0].class
211 assert_nothing_raised { Process.kill(0, pid) }
212 master_log = "#{@tmpdir}/test_stderr.#{pid}.log"
213 wait_master_ready(master_log)
214 File.truncate(master_log, 0)
217 assert_nothing_raised do
219 hit(["http://#{@addr}:#{@port}/#{i}"])
220 i == kill_point and Process.kill(:HUP, pid)
223 wait_master_ready(master_log)
224 assert File.exist?(pid_file), "pid=#{pid_file} exists"
225 new_pid = File.read(pid_file).to_i
226 assert_not_equal pid, new_pid
227 assert_nothing_raised { Process.kill(0, new_pid) }
228 assert_nothing_raised { Process.kill(:QUIT, new_pid) }
231 def wait_for_file(path)
232 tries = DEFAULT_TRIES
233 while (tries -= 1) > 0 && ! File.exist?(path)
236 assert File.exist?(path), "path=#{path} exists #{caller.inspect}"
241 ObjectSpace.each_object(Tempfile) do |tmp|
242 ObjectSpace.undefine_finalizer(tmp)
248 # can't waitpid on detached processes
249 def wait_for_death(pid)
250 tries = DEFAULT_TRIES
251 while (tries -= 1) > 0
255 Process.waitpid(pid, Process::WNOHANG)
263 raise "PID:#{pid} never died!"
266 # executes +cmd+ and chunks its STDOUT
267 def chunked_spawn(stdout, *cmd)
272 crd.sync = cwr.sync = true
282 buf = crd.readpartial(16384)
283 stdout.write("#{'%x' % buf.size}\r\n#{buf}")
285 stdout.write("0\r\n")
286 pid, status = Process.waitpid(pid)
287 exit status.exitstatus