1 # -*- encoding: binary -*-
2 # frozen_string_literal: false
4 # Copyright (c) 2005 Zed A. Shaw
5 # You can redistribute it and/or modify it under the same terms as Ruby 1.8 or
6 # the GPLv2+ (GPLv3+ preferred)
8 # Additional work donated by contributors. See git history
9 # for more information.
11 STDIN.sync = STDOUT.sync = STDERR.sync = true # buffering makes debugging hard
13 # FIXME: move curl-dependent tests into t/
14 ENV['NO_PROXY'] ||= ENV['UNICORN_TEST_ADDR'] || '127.0.0.1'
16 # Some tests watch a log file or a pid file to spring up to check state
17 # Can't rely on inotify on non-Linux and logging to a pipe makes things
39 unless RUBY_VERSION < '3.1'
40 warn "Unicorn was only tested against MRI up to 3.0.\n" \
41 "It might not properly work with #{RUBY_VERSION}"
48 new_out = File.open("test_stdout.#$$.log", "a")
49 new_err = File.open("test_stderr.#$$.log", "a")
50 new_out.sync = new_err.sync = true
52 if tail = ENV['TAIL'] # "tail -F" if GNU, "tail -f" otherwise
57 pid = Process.spawn(*cmd, { 1 => 2, :pgroup => true })
58 sleep 0.1 # wait for tail(1) to startup
60 STDERR.reopen(new_err)
61 STDOUT.reopen(new_out)
62 STDERR.sync = STDOUT.sync = true
66 File.unlink(new_out.path) rescue nil
67 File.unlink(new_err.path) rescue nil
74 STDERR.reopen(orig_err)
75 STDOUT.reopen(orig_out)
76 Process.kill(:TERM, pid) if pid
80 # which(1) exit codes cannot be trusted on some systems
81 # We use UNIX shell utilities in some tests because we don't trust
82 # ourselves to write Ruby 100% correctly :)
84 ex = ENV['PATH'].split(/:/).detect do |x|
87 end or warn "`#{bin}' not found in PATH=#{ENV['PATH']}"
91 # Either takes a string to do a get request against, or a tuple of [URI, HTTP] where
92 # HTTP is some kind of Net::HTTP request object (POST, HEAD, etc.)
99 u = 'http://127.0.0.1:8080/' if u == 'http://0.0.0.0:8080/'
100 res = Net::HTTP.get(URI.parse(u))
102 url = URI.parse(u[0])
103 res = Net::HTTP.new(url.host, url.port).start {|h| h.request(u[1]) }
106 assert res != nil, "Didn't get a response: #{u}"
113 # unused_port provides an unused port on +addr+ usable for TCP that is
114 # guaranteed to be unused across all unicorn builds on that system. It
115 # prevents race conditions by using a lock file other unicorn builds
116 # will see. This is required if you perform several builds in parallel
117 # with a continuous integration system or run tests in parallel via
118 # gmake. This is NOT guaranteed to be race-free if you run other
119 # processes that bind to random ports for testing (but the window
120 # for a race condition is very small). You may also set UNICORN_TEST_ADDR
121 # to override the default test address (127.0.0.1).
122 def unused_port(addr = '127.0.0.1')
128 port = base + rand(32768 - base)
129 while port == Unicorn::Const::DEFAULT_PORT
130 port = base + rand(32768 - base)
133 sock = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0)
134 sock.bind(Socket.pack_sockaddr_in(port, addr))
136 rescue Errno::EADDRINUSE, Errno::EACCES
137 sock.close rescue nil
138 retry if (retries -= 1) >= 0
141 # since we'll end up closing the random port we just got, there's a race
142 # condition could allow the random port we just chose to reselect itself
143 # when running tests in parallel with gmake. Create a lock file while
144 # we have the port here to ensure that does not happen .
145 lock_path = "#{Dir::tmpdir}/unicorn_test.#{addr}:#{port}.lock"
146 File.open(lock_path, File::WRONLY|File::CREAT|File::EXCL, 0600).close
147 at_exit { File.unlink(lock_path) rescue nil }
149 sock.close rescue nil
152 sock.close rescue nil
165 # sometimes the server may not come up right away
166 def retry_hit(uris = [])
167 tries = DEFAULT_TRIES
170 rescue Errno::EINVAL, Errno::ECONNREFUSED => err
179 def assert_shutdown(pid)
180 wait_master_ready("test_stderr.#{pid}.log")
181 Process.kill(:QUIT, pid)
182 pid, status = Process.waitpid2(pid)
183 assert status.success?, "exited successfully"
186 def wait_workers_ready(path, nr_workers)
187 tries = DEFAULT_TRIES
189 while (tries -= 1) > 0
191 lines = File.readlines(path).grep(/worker=\d+ ready/)
192 lines.size == nr_workers and return
197 raise "#{nr_workers} workers never became ready:" \
198 "\n\t#{lines.join("\n\t")}\n"
201 def wait_master_ready(master_log)
202 tries = DEFAULT_TRIES
203 while (tries -= 1) > 0
205 File.readlines(master_log).grep(/master process ready/)[0] and return
210 raise "master process never became ready"
213 def reexec_usr2_quit_test(pid, pid_file)
214 assert File.exist?(pid_file), "pid file OK"
215 assert ! File.exist?("#{pid_file}.oldbin"), "oldbin pid file"
216 Process.kill(:USR2, pid)
217 retry_hit(["http://#{@addr}:#{@port}/"])
218 wait_for_file("#{pid_file}.oldbin")
219 wait_for_file(pid_file)
221 old_pid = File.read("#{pid_file}.oldbin").to_i
222 new_pid = File.read(pid_file).to_i
224 # kill old master process
225 assert_not_equal pid, new_pid
226 assert_equal pid, old_pid
227 Process.kill(:QUIT, old_pid)
228 retry_hit(["http://#{@addr}:#{@port}/"])
229 wait_for_death(old_pid)
230 assert_equal new_pid, File.read(pid_file).to_i
231 retry_hit(["http://#{@addr}:#{@port}/"])
232 Process.kill(:QUIT, new_pid)
235 def reexec_basic_test(pid, pid_file)
236 results = retry_hit(["http://#{@addr}:#{@port}/"])
237 assert_equal String, results[0].class
239 master_log = "#{@tmpdir}/test_stderr.#{pid}.log"
240 wait_master_ready(master_log)
241 File.truncate(master_log, 0)
245 hit(["http://#{@addr}:#{@port}/#{i}"])
246 i == kill_point and Process.kill(:HUP, pid)
248 wait_master_ready(master_log)
249 assert File.exist?(pid_file), "pid=#{pid_file} exists"
250 new_pid = File.read(pid_file).to_i
251 assert_not_equal pid, new_pid
252 Process.kill(0, new_pid)
253 Process.kill(:QUIT, new_pid)
256 def wait_for_file(path)
257 tries = DEFAULT_TRIES
258 while (tries -= 1) > 0 && ! File.exist?(path)
261 assert File.exist?(path), "path=#{path} exists #{caller.inspect}"
266 ObjectSpace.each_object(Tempfile) do |tmp|
267 ObjectSpace.undefine_finalizer(tmp)
273 # can't waitpid on detached processes
274 def wait_for_death(pid)
275 tries = DEFAULT_TRIES
276 while (tries -= 1) > 0
280 Process.waitpid(pid, Process::WNOHANG)
288 raise "PID:#{pid} never died!"
291 def reset_sig_handlers
292 %w(WINCH QUIT INT TERM USR1 USR2 HUP TTIN TTOU CHLD).each do |sig|
297 def tcp_socket(*args)
298 sock = TCPSocket.new(*args)
299 sock.nonblock = false
303 def unix_socket(*args)
304 sock = UNIXSocket.new(*args)
305 sock.nonblock = false