test/exec: close-on-exec all Tempfiles
[ruby-mogilefs-client.git] / test / exec.rb
blob6a6c8320d999a19dda3a121fe021e8b9324c0e36
1 # -*- encoding: binary -*-
2 $stdout.sync = $stderr.sync = true
3 Thread.abort_on_exception = true
4 require 'test/unit'
5 require 'securerandom'
6 require 'tempfile'
7 require 'digest'
8 require 'stringio'
9 require 'pp'
10 require 'mogilefs'
12 module TestExec
13   def uuid
14     SecureRandom.uuid
15   rescue NoMethodError
16     ary = SecureRandom.random_bytes(16).unpack("NnnnnN")
17     ary[2] = (ary[2] & 0x0fff) | 0x4000
18     ary[3] = (ary[3] & 0x3fff) | 0x8000
19     "%08x-%04x-%04x-%04x-%04x%08x" % ary
20   end
22   def yield_for_monitor_update # mogilefsd should update every 4 seconds
23     50.times do
24       yield
25       sleep 0.1
26     end
27   end
29   def mogadm(*args)
30     x("mogadm", "--trackers=#{@trackers.join(',')}", *args)
31   end
33   def x(*cmd)
34     out, err = tmpfile("out"), tmpfile("err")
35     puts cmd.join(' ') if $VERBOSE
36     pid = fork do
37       $stderr.reopen(err.path, "a")
38       $stdout.reopen(out.path, "a")
39       out.close
40       err.close
41       ObjectSpace.each_object(Tempfile) do |tmp|
42         next if tmp.closed?
43         ObjectSpace.undefine_finalizer(tmp)
44         tmp.close_on_exec = true if tmp.respond_to?(:close_on_exec=)
45       end
46       exec(*cmd)
47     end
48     _, status = Process.waitpid2(pid)
49     out.rewind
50     err.rewind
51     [ status, out, err ]
52   end
54   def mogadm!(*args)
55     status, out, err = mogadm(*args)
56     assert status.success?, "#{status.inspect} / #{out.read} / #{err.read}"
57     [ status, out, err ]
58   end
60   def x!(*cmd)
61     status, out, err = x(*cmd)
62     assert status.success?, "#{status.inspect} / #{out.read} / #{err.read}"
63     [ status, out, err ]
64   end
66   def tmpfile(name)
67     tmp = Tempfile.new(name)
68     defined?(@to_close) or @to_close = []
69     @to_close << tmp
70     tmp
71   end
72 end