From 3733ace20b06f69e11b34a714a266306813616e9 Mon Sep 17 00:00:00 2001 From: Kazuki Yamaguchi Date: Fri, 19 Aug 2016 12:30:29 +0900 Subject: test/test_ssl: fix failure on Windows Due to the difference in error handling, the error raised by SSLSocket#connect may differ. --- test/test_ssl.rb | 95 ++++++++++++++++++++++++++++++++------------------------ test/utils.rb | 2 +- 2 files changed, 56 insertions(+), 41 deletions(-) (limited to 'test') diff --git a/test/test_ssl.rb b/test/test_ssl.rb index e6964d93..1b9548a3 100644 --- a/test/test_ssl.rb +++ b/test/test_ssl.rb @@ -196,16 +196,14 @@ class OpenSSL::TestSSL < OpenSSL::SSLTestCase def test_client_auth_failure vflag = OpenSSL::SSL::VERIFY_PEER|OpenSSL::SSL::VERIFY_FAIL_IF_NO_PEER_CERT start_server(vflag, true, :ignore_listener_error => true){|server, port| - assert_raise(OpenSSL::SSL::SSLError, Errno::ECONNRESET){ - sock = TCPSocket.new("127.0.0.1", port) - ssl = OpenSSL::SSL::SSLSocket.new(sock) - ssl.sync_close = true - begin - ssl.connect - ensure - ssl.close - end - } + sock = TCPSocket.new("127.0.0.1", port) + ssl = OpenSSL::SSL::SSLSocket.new(sock) + ssl.sync_close = true + begin + assert_handshake_error { ssl.connect } + ensure + ssl.close + end } end @@ -246,13 +244,11 @@ class OpenSSL::TestSSL < OpenSSL::SSLTestCase server_connect(port, ctx) { } } - assert_raise(OpenSSL::SSL::SSLError) { - ctx = OpenSSL::SSL::SSLContext.new - ctx.client_cert_cb = Proc.new{ |ssl| - [@cli_cert, @cli_key.public_key] - } - server_connect(port, ctx) { } + ctx = OpenSSL::SSL::SSLContext.new + ctx.client_cert_cb = Proc.new{ |ssl| + [@cli_cert, @cli_key.public_key] } + assert_handshake_error { server_connect(port, ctx) } end end @@ -938,7 +934,7 @@ class OpenSSL::TestSSL < OpenSSL::SSLTestCase if expected_ok assert_nothing_raised { ssl.connect } else - assert_raise(OpenSSL::SSL::SSLError) { ssl.connect } + assert_handshake_error { ssl.connect } end ensure ssl.close if ssl @@ -988,10 +984,6 @@ class OpenSSL::TestSSL < OpenSSL::SSLTestCase } end - # different OpenSSL versions react differently when facing a SSL/TLS version - # that has been marked as forbidden, therefore either of these may be raised - HANDSHAKE_ERRORS = [OpenSSL::SSL::SSLError, Errno::ECONNRESET] - if OpenSSL::SSL::SSLContext::METHODS.include?(:TLSv1) && OpenSSL::SSL::SSLContext::METHODS.include?(:SSLv3) def test_forbid_ssl_v3_for_client @@ -999,7 +991,7 @@ if OpenSSL::SSL::SSLContext::METHODS.include?(:TLSv1) && OpenSSL::SSL::SSLContex start_server_version(:SSLv23, ctx_proc) { |server, port| ctx = OpenSSL::SSL::SSLContext.new ctx.ssl_version = :SSLv3 - assert_raise(*HANDSHAKE_ERRORS) { server_connect(port, ctx) } + assert_handshake_error { server_connect(port, ctx) } } end @@ -1007,7 +999,7 @@ if OpenSSL::SSL::SSLContext::METHODS.include?(:TLSv1) && OpenSSL::SSL::SSLContex start_server_version(:SSLv3) { |server, port| ctx = OpenSSL::SSL::SSLContext.new ctx.options = OpenSSL::SSL::OP_ALL | OpenSSL::SSL::OP_NO_SSLv3 - assert_raise(*HANDSHAKE_ERRORS) { server_connect(port, ctx) } + assert_handshake_error { server_connect(port, ctx) } } end @@ -1026,7 +1018,7 @@ if OpenSSL::SSL::SSLContext::METHODS.include? :TLSv1_1 start_server_version(:SSLv23, ctx_proc) { |server, port| ctx = OpenSSL::SSL::SSLContext.new ctx.ssl_version = :TLSv1 - assert_raise(*HANDSHAKE_ERRORS) { server_connect(port, ctx) } + assert_handshake_error { server_connect(port, ctx) } } end @@ -1034,7 +1026,7 @@ if OpenSSL::SSL::SSLContext::METHODS.include? :TLSv1_1 start_server_version(:TLSv1) { |server, port| ctx = OpenSSL::SSL::SSLContext.new ctx.options = OpenSSL::SSL::OP_ALL | OpenSSL::SSL::OP_NO_TLSv1 - assert_raise(*HANDSHAKE_ERRORS) { server_connect(port, ctx) } + assert_handshake_error { server_connect(port, ctx) } } end @@ -1055,7 +1047,7 @@ if OpenSSL::SSL::SSLContext::METHODS.include? :TLSv1_2 start_server_version(:SSLv23, ctx_proc) { |server, port| ctx = OpenSSL::SSL::SSLContext.new ctx.ssl_version = :TLSv1_1 - assert_raise(*HANDSHAKE_ERRORS) { server_connect(port, ctx) } + assert_handshake_error { server_connect(port, ctx) } } end if defined?(OpenSSL::SSL::OP_NO_TLSv1_1) @@ -1063,7 +1055,7 @@ if OpenSSL::SSL::SSLContext::METHODS.include? :TLSv1_2 start_server_version(:TLSv1_1) { |server, port| ctx = OpenSSL::SSL::SSLContext.new ctx.options = OpenSSL::SSL::OP_ALL | OpenSSL::SSL::OP_NO_TLSv1_1 - assert_raise(*HANDSHAKE_ERRORS) { server_connect(port, ctx) } + assert_handshake_error { server_connect(port, ctx) } } end if defined?(OpenSSL::SSL::OP_NO_TLSv1_1) @@ -1072,7 +1064,7 @@ if OpenSSL::SSL::SSLContext::METHODS.include? :TLSv1_2 start_server_version(:SSLv23, ctx_proc) { |server, port| ctx = OpenSSL::SSL::SSLContext.new ctx.ssl_version = :TLSv1_2 - assert_raise(*HANDSHAKE_ERRORS) { server_connect(port, ctx) } + assert_handshake_error { server_connect(port, ctx) } } end if defined?(OpenSSL::SSL::OP_NO_TLSv1_2) @@ -1080,7 +1072,7 @@ if OpenSSL::SSL::SSLContext::METHODS.include? :TLSv1_2 start_server_version(:TLSv1_2) { |server, port| ctx = OpenSSL::SSL::SSLContext.new ctx.options = OpenSSL::SSL::OP_ALL | OpenSSL::SSL::OP_NO_TLSv1_2 - assert_raise(*HANDSHAKE_ERRORS) { server_connect(port, ctx) } + assert_handshake_error { server_connect(port, ctx) } } end if defined?(OpenSSL::SSL::OP_NO_TLSv1_2) @@ -1116,16 +1108,31 @@ if OpenSSL::OPENSSL_VERSION_NUMBER >= 0x10002000 end def test_alpn_protocol_selection_cancel - ctx_proc = Proc.new { |ctx| - ctx.alpn_select_cb = -> (protocols) { nil } + sock1, sock2 = socketpair + + ctx1 = OpenSSL::SSL::SSLContext.new + ctx1.ciphers = "aNULL" + ctx1.security_level = 0 + ctx1.alpn_select_cb = -> (protocols) { nil } + ssl1 = OpenSSL::SSL::SSLSocket.new(sock1, ctx1) + + ctx2 = OpenSSL::SSL::SSLContext.new + ctx2.ciphers = "aNULL" + ctx2.security_level = 0 + ctx2.alpn_protocols = ["http/1.1"] + ssl2 = OpenSSL::SSL::SSLSocket.new(sock2, ctx2) + + t = Thread.new { + assert_handshake_error { ssl2.connect } } - assert_raise(MiniTest::Assertion) do # minitest/assertion comes from `assert_join_threads` - start_server_version(:SSLv23, ctx_proc) { |server, port| - ctx = OpenSSL::SSL::SSLContext.new - ctx.alpn_protocols = ["http/1.1"] - assert_raise(OpenSSL::SSL::SSLError) { server_connect(port, ctx) } - } - end + assert_raise(TypeError) { ssl1.accept } + ensure + sock1&.close + sock2&.close + ssl1&.close + ssl2&.close + t&.kill + t&.join end end @@ -1183,7 +1190,7 @@ if OpenSSL::OPENSSL_VERSION_NUMBER > 0x10001000 && start_server_version(:SSLv23, ctx_proc) { |server, port| ctx = OpenSSL::SSL::SSLContext.new ctx.npn_select_cb = -> (protocols) { protocols.first } - assert_raise(*HANDSHAKE_ERRORS) { server_connect(port, ctx) } + assert_handshake_error { server_connect(port, ctx) } } end @@ -1192,7 +1199,7 @@ if OpenSSL::OPENSSL_VERSION_NUMBER > 0x10001000 && start_server_version(:SSLv23, ctx_proc) { |server, port| ctx = OpenSSL::SSL::SSLContext.new ctx.npn_select_cb = -> (protocols) { "a" * 256 } - assert_raise(*HANDSHAKE_ERRORS) { server_connect(port, ctx) } + assert_handshake_error { server_connect(port, ctx) } } end @@ -1346,6 +1353,14 @@ end sock.close end end + + def assert_handshake_error + # different OpenSSL versions react differently when facing a SSL/TLS version + # that has been marked as forbidden, therefore either of these may be raised + assert_raise(OpenSSL::SSL::SSLError, Errno::ECONNRESET) { + yield + } + end end end diff --git a/test/utils.rb b/test/utils.rb index 1237a511..5de26601 100644 --- a/test/utils.rb +++ b/test/utils.rb @@ -284,7 +284,7 @@ AQjjxMXhwULlmuR/K+WwlaZPiLIBYalLAZQ7ZbOPeVkJ8ePao0eLAgEC return end ssl = ssls.accept - rescue OpenSSL::SSL::SSLError + rescue OpenSSL::SSL::SSLError, Errno::ECONNRESET if ignore_listener_error retry else -- cgit v1.2.3 From 6cae7d56cb5bbd72028bfc53cef7247dec21c899 Mon Sep 17 00:00:00 2001 From: Kazuki Yamaguchi Date: Mon, 15 Aug 2016 00:16:50 +0900 Subject: test: remove unused methods They are imported from Ruby tree but unused in this tree. --- test/envutil.rb | 372 +----------------------------------------------- test/find_executable.rb | 21 --- test/memory_status.rb | 134 ----------------- 3 files changed, 6 insertions(+), 521 deletions(-) delete mode 100644 test/find_executable.rb delete mode 100644 test/memory_status.rb (limited to 'test') diff --git a/test/envutil.rb b/test/envutil.rb index 5cd8b511..da304102 100644 --- a/test/envutil.rb +++ b/test/envutil.rb @@ -1,36 +1,10 @@ # -*- coding: us-ascii -*- -require "open3" require "timeout" -require_relative "find_executable" - -unless defined?(MiniTest) - module MiniTest - Assertion = Test::Unit::AssertionFailedError - end -end +require "rbconfig" module EnvUtil def rubybin - if ruby = ENV["RUBY"] - return ruby - end - ruby = "ruby" - exeext = RbConfig::CONFIG["EXEEXT"] - rubyexe = (ruby + exeext if exeext and !exeext.empty?) - 3.times do - if File.exist? ruby and File.executable? ruby and !File.directory? ruby - return File.expand_path(ruby) - end - if rubyexe and File.exist? rubyexe and File.executable? rubyexe - return File.expand_path(rubyexe) - end - ruby = File.join("..", ruby) - end - if defined?(RbConfig.ruby) - RbConfig.ruby - else - "ruby" - end + ENV["RUBY"] || RbConfig.ruby end module_function :rubybin @@ -117,31 +91,6 @@ module EnvUtil end module_function :invoke_ruby - alias rubyexec invoke_ruby - class << self - alias rubyexec invoke_ruby - end - - def verbose_warning - class << (stderr = "") - alias write << - end - stderr, $stderr, verbose, $VERBOSE = $stderr, stderr, $VERBOSE, true - yield stderr - return $stderr - ensure - stderr, $stderr, $VERBOSE = $stderr, stderr, verbose - end - module_function :verbose_warning - - def default_warning - verbose, $VERBOSE = $VERBOSE, false - yield - ensure - $VERBOSE = verbose - end - module_function :default_warning - def suppress_warning verbose, $VERBOSE = $VERBOSE, nil yield @@ -150,54 +99,6 @@ module EnvUtil end module_function :suppress_warning - def under_gc_stress(stress = true) - stress, GC.stress = GC.stress, stress - yield - ensure - GC.stress = stress - end - module_function :under_gc_stress - - def with_default_external(enc) - verbose, $VERBOSE = $VERBOSE, nil - origenc, Encoding.default_external = Encoding.default_external, enc - $VERBOSE = verbose - yield - ensure - verbose, $VERBOSE = $VERBOSE, nil - Encoding.default_external = origenc - $VERBOSE = verbose - end - module_function :with_default_external - - def with_default_internal(enc) - verbose, $VERBOSE = $VERBOSE, nil - origenc, Encoding.default_internal = Encoding.default_internal, enc - $VERBOSE = verbose - yield - ensure - verbose, $VERBOSE = $VERBOSE, nil - Encoding.default_internal = origenc - $VERBOSE = verbose - end - module_function :with_default_internal - - def labeled_module(name, &block) - Module.new do - singleton_class.class_eval {define_method(:to_s) {name}; alias inspect to_s} - class_eval(&block) if block - end - end - module_function :labeled_module - - def labeled_class(name, superclass = Object, &block) - Class.new(superclass) do - singleton_class.class_eval {define_method(:to_s) {name}; alias inspect to_s} - class_eval(&block) if block - end - end - module_function :labeled_class - if /darwin/ =~ RUBY_PLATFORM DIAGNOSTIC_REPORTS_PATH = File.expand_path("~/Library/Logs/DiagnosticReports") DIAGNOSTIC_REPORTS_TIMEFORMAT = '%Y-%m-%d-%H%M%S' @@ -230,65 +131,6 @@ end module Test module Unit module Assertions - public - def assert_valid_syntax(code, fname = caller_locations(1, 1)[0], mesg = fname.to_s, verbose: nil) - code = code.dup.force_encoding("ascii-8bit") - code.sub!(/\A(?:\xef\xbb\xbf)?(\s*\#.*$)*(\n)?/n) { - "#$&#{"\n" if $1 && !$2}BEGIN{throw tag, :ok}\n" - } - code.force_encoding(Encoding::UTF_8) - verbose, $VERBOSE = $VERBOSE, verbose - yield if defined?(yield) - case - when Array === fname - fname, line = *fname - when defined?(fname.path) && defined?(fname.lineno) - fname, line = fname.path, fname.lineno - else - line = 0 - end - assert_nothing_raised(SyntaxError, mesg) do - assert_equal(:ok, catch {|tag| eval(code, binding, fname, line)}, mesg) - end - ensure - $VERBOSE = verbose - end - - def assert_syntax_error(code, error, fname = caller_locations(1, 1)[0], mesg = fname.to_s) - code = code.dup.force_encoding("ascii-8bit") - code.sub!(/\A(?:\xef\xbb\xbf)?(\s*\#.*$)*(\n)?/n) { - "#$&#{"\n" if $1 && !$2}BEGIN{throw tag, :ng}\n" - } - code.force_encoding("us-ascii") - verbose, $VERBOSE = $VERBOSE, nil - yield if defined?(yield) - case - when Array === fname - fname, line = *fname - when defined?(fname.path) && defined?(fname.lineno) - fname, line = fname.path, fname.lineno - else - line = 0 - end - e = assert_raise(SyntaxError, mesg) do - catch {|tag| eval(code, binding, fname, line)} - end - assert_match(error, e.message, mesg) - ensure - $VERBOSE = verbose - end - - def assert_normal_exit(testsrc, message = '', child_env: nil, **opt) - assert_valid_syntax(testsrc, caller_locations(1, 1)[0]) - if child_env - child_env = [child_env] - else - child_env = [] - end - out, _, status = EnvUtil.invoke_ruby(child_env + %W'-W0', testsrc, true, :merge_to_stdout, **opt) - assert !status.signaled?, FailDesc[status, message, out] - end - FailDesc = proc do |status, message = "", out = ""| pid = status.pid now = Time.now @@ -321,42 +163,6 @@ module Test faildesc end - def assert_in_out_err(args, test_stdin = "", test_stdout = [], test_stderr = [], message = nil, **opt) - stdout, stderr, status = EnvUtil.invoke_ruby(args, test_stdin, true, true, **opt) - if signo = status.termsig - sleep 0.1 - EnvUtil.diagnostic_reports(Signal.signame(signo), EnvUtil.rubybin, status.pid, Time.now) - end - if block_given? - raise "test_stdout ignored, use block only or without block" if test_stdout != [] - raise "test_stderr ignored, use block only or without block" if test_stderr != [] - yield(stdout.lines.map {|l| l.chomp }, stderr.lines.map {|l| l.chomp }, status) - else - errs = [] - [[test_stdout, stdout], [test_stderr, stderr]].each do |exp, act| - begin - if exp.is_a?(Regexp) - assert_match(exp, act, message) - else - assert_equal(exp, act.lines.map {|l| l.chomp }, message) - end - rescue MiniTest::Assertion => e - errs << e.message - message = nil - end - end - raise MiniTest::Assertion, errs.join("\n---\n") unless errs.empty? - status - end - end - - def assert_ruby_status(args, test_stdin="", message=nil, **opt) - out, _, status = EnvUtil.invoke_ruby(args, test_stdin, true, :merge_to_stdout, **opt) - assert(!status.signaled?, FailDesc[status, message, out]) - message ||= "ruby exit status is not success:" - assert(status.success?, "#{message} (#{status.inspect})") - end - ABORT_SIGNALS = Signal.list.values_at(*%w"ILL ABRT BUS SEGV") def assert_separately(args, file = nil, line = nil, src, ignore_stderr: nil, **opt) @@ -413,78 +219,6 @@ eom raise marshal_error if marshal_error end - def assert_warning(pat, msg = nil) - stderr = EnvUtil.verbose_warning { yield } - msg = message(msg) {diff pat, stderr} - assert(pat === stderr, msg) - end - - def assert_warn(*args) - assert_warning(*args) {$VERBOSE = false; yield} - end - - case RUBY_PLATFORM - when /solaris2\.(?:9|[1-9][0-9])/i # Solaris 9, 10, 11,... - bits = [nil].pack('p').size == 8 ? 64 : 32 - if ENV['LD_PRELOAD'].to_s.empty? && - ENV["LD_PRELOAD_#{bits}"].to_s.empty? && - (ENV['UMEM_OPTIONS'].to_s.empty? || - ENV['UMEM_OPTIONS'] == 'backend=mmap') then - envs = { - 'LD_PRELOAD' => 'libumem.so', - 'UMEM_OPTIONS' => 'backend=mmap' - } - args = [ - envs, - "--disable=gems", - "-v", "-", - ] - _, err, status = EnvUtil.invoke_ruby(args, "exit(0)", true, true) - if status.exitstatus == 0 && err.to_s.empty? then - NO_MEMORY_LEAK_ENVS = envs - end - end - end #case RUBY_PLATFORM - - def assert_no_memory_leak(args, prepare, code, message=nil, limit: 1.5, rss: false, **opt) - require_relative 'memory_status' - token = "\e[7;1m#{$$.to_s}:#{Time.now.strftime('%s.%L')}:#{rand(0x10000).to_s(16)}:\e[m" - token_dump = token.dump - token_re = Regexp.quote(token) - envs = args.shift if Array === args and Hash === args.first - args = [ - "-r", File.expand_path("../memory_status", __FILE__), - *args, - "-v", "-", - ] - if defined? NO_MEMORY_LEAK_ENVS then - envs ||= {} - newenvs = envs.merge(NO_MEMORY_LEAK_ENVS) { |_, _, _| break } - envs = newenvs if newenvs - end - args.unshift(envs) if envs - cmd = [ - 'END {STDERR.puts '"#{token_dump}"'"FINAL=#{Memory::Status.new}"}', - prepare, - 'STDERR.puts('"#{token_dump}"'"START=#{$initial_status = Memory::Status.new}")', - '$initial_size = $initial_status.size', - code, - 'GC.start', - ].join("\n") - _, err, status = EnvUtil.invoke_ruby(args, cmd, true, true, **opt) - before = err.sub!(/^#{token_re}START=(\{.*\})\n/, '') && Memory::Status.parse($1) - after = err.sub!(/^#{token_re}FINAL=(\{.*\})\n/, '') && Memory::Status.parse($1) - assert_equal([true, ""], [status.success?, err], message) - ([:size, (rss && :rss)] & after.members).each do |n| - b = before[n] - a = after[n] - next unless a > 0 and b > 0 - assert_operator(a.fdiv(b), :<, limit, message(message) {"#{n}: #{b} => #{a}"}) - end - rescue LoadError - pend - end - def message msg = nil, ending = ".", &default proc { msg = msg.call.chomp(".") if Proc === msg @@ -493,57 +227,6 @@ eom } end - def assert_is_minus_zero(f) - assert(1.0/f == -Float::INFINITY, "#{f} is not -0.0") - end - - def assert_file - AssertFile - end - - # pattern_list is an array which contains regexp and :*. - # :* means any sequence. - # - # pattern_list is anchored. - # Use [:*, regexp, :*] for non-anchored match. - def assert_pattern_list(pattern_list, actual, message=nil) - rest = actual - anchored = true - pattern_list.each_with_index {|pattern, i| - if pattern == :* - anchored = false - else - if anchored - match = /\A#{pattern}/.match(rest) - else - match = pattern.match(rest) - end - unless match - msg = message(msg) { - expect_msg = "Expected #{mu_pp pattern}\n" - if /\n[^\n]/ =~ rest - actual_mesg = "to match\n" - rest.scan(/.*\n+/) { - actual_mesg << ' ' << $&.inspect << "+\n" - } - actual_mesg.sub!(/\+\n\z/, '') - else - actual_mesg = "to match #{mu_pp rest}" - end - actual_mesg << "\nafter #{i} patterns with #{actual.length - rest.length} characters" - expect_msg + actual_mesg - } - assert false, msg - end - rest = match.post_match - anchored = true - end - } - if anchored - assert_equal("", rest) - end - end - # threads should respond to shift method. # Array can be used. def assert_join_threads(threads, message = nil) @@ -571,7 +254,7 @@ eom if message msg = "#{message}\n#{msg}" end - raise MiniTest::Assertion, msg + raise Test::Unit::AssertionFailedError, msg end values end @@ -608,12 +291,10 @@ eom end ex = m = nil - EnvUtil.with_default_internal(expected.encoding) do - ex = assert_raise(exception, msg || "Exception(#{exception}) with message matches to #{expected.inspect}") do - yield - end - m = ex.message + ex = assert_raise(exception, msg || "Exception(#{exception}) with message matches to #{expected.inspect}") do + yield end + m = ex.message msg = message(msg, "") {"Expected Exception(#{exception}) was raised, but the message doesn't match"} if assert == :assert_equal @@ -625,47 +306,6 @@ eom end ex end - - class << (AssertFile = Struct.new(:failure_message).new) - include Assertions - def assert_file_predicate(predicate, *args) - if /\Anot_/ =~ predicate - predicate = $' - neg = " not" - end - result = File.__send__(predicate, *args) - result = !result if neg - mesg = "Expected file " << args.shift.inspect - mesg << "#{neg} to be #{predicate}" - mesg << mu_pp(args).sub(/\A\[(.*)\]\z/m, '(\1)') unless args.empty? - mesg << " #{failure_message}" if failure_message - assert(result, mesg) - end - alias method_missing assert_file_predicate - - def for(message) - clone.tap {|a| a.failure_message = message} - end - end - end - end -end - -begin - require 'rbconfig' -rescue LoadError -else - module RbConfig - @ruby = EnvUtil.rubybin - class << self - undef ruby if method_defined?(:ruby) - attr_reader :ruby end - dir = File.dirname(ruby) - name = File.basename(ruby, CONFIG['EXEEXT']) - CONFIG['bindir'] = dir - CONFIG['ruby_install_name'] = name - CONFIG['RUBY_INSTALL_NAME'] = name - Gem::ConfigMap[:bindir] = dir if defined?(Gem::ConfigMap) end end diff --git a/test/find_executable.rb b/test/find_executable.rb deleted file mode 100644 index 4ba9a053..00000000 --- a/test/find_executable.rb +++ /dev/null @@ -1,21 +0,0 @@ -require "rbconfig" - -module EnvUtil - def find_executable(cmd, *args) - exts = RbConfig::CONFIG["EXECUTABLE_EXTS"].split | [RbConfig::CONFIG["EXEEXT"]] - ENV["PATH"].split(File::PATH_SEPARATOR).each do |path| - next if path.empty? - path = File.join(path, cmd) - exts.each do |ext| - cmdline = [path + ext, *args] - begin - return cmdline if yield(IO.popen(cmdline, "r", err: [:child, :out], &:read)) - rescue - next - end - end - end - nil - end - module_function :find_executable -end diff --git a/test/memory_status.rb b/test/memory_status.rb deleted file mode 100644 index 5347e34c..00000000 --- a/test/memory_status.rb +++ /dev/null @@ -1,134 +0,0 @@ -module Memory - keys = [] - vals = [] - - case - when File.exist?(procfile = "/proc/self/status") && (pat = /^Vm(\w+):\s+(\d+)/) =~ File.binread(procfile) - PROC_FILE = procfile - VM_PAT = pat - def self.read_status - IO.foreach(PROC_FILE, encoding: Encoding::ASCII_8BIT) do |l| - yield($1.downcase.intern, $2.to_i * 1024) if VM_PAT =~ l - end - end - - read_status {|k, v| keys << k; vals << v} - - when /mswin|mingw/ =~ RUBY_PLATFORM - begin - require 'fiddle/import' - rescue LoadError - $LOAD_PATH.unshift File.join(File.join(__dir__, '..'), 'lib') - require_relative 'envutil' - EnvUtil.suppress_warning do - require 'dl/import' - end - end - begin - require 'fiddle/types' - rescue LoadError - require_relative 'envutil' - EnvUtil.suppress_warning do - require 'dl/types' - end - end - - module Win32 - begin - extend Fiddle::Importer - rescue NameError - extend DL::Importer - end - dlload "kernel32.dll", "psapi.dll" - begin - include Fiddle::Win32Types - rescue NameError - include DL::Win32Types - end - typealias "SIZE_T", "size_t" - - PROCESS_MEMORY_COUNTERS = struct [ - "DWORD cb", - "DWORD PageFaultCount", - "SIZE_T PeakWorkingSetSize", - "SIZE_T WorkingSetSize", - "SIZE_T QuotaPeakPagedPoolUsage", - "SIZE_T QuotaPagedPoolUsage", - "SIZE_T QuotaPeakNonPagedPoolUsage", - "SIZE_T QuotaNonPagedPoolUsage", - "SIZE_T PagefileUsage", - "SIZE_T PeakPagefileUsage", - ] - - typealias "PPROCESS_MEMORY_COUNTERS", "PROCESS_MEMORY_COUNTERS*" - - extern "HANDLE GetCurrentProcess()", :stdcall - extern "BOOL GetProcessMemoryInfo(HANDLE, PPROCESS_MEMORY_COUNTERS, DWORD)", :stdcall - - module_function - def memory_info - size = PROCESS_MEMORY_COUNTERS.size - data = PROCESS_MEMORY_COUNTERS.malloc - data.cb = size - data if GetProcessMemoryInfo(GetCurrentProcess(), data, size) - end - end - - keys << :peak << :size - def self.read_status - if info = Win32.memory_info - yield :peak, info.PeakPagefileUsage - yield :size, info.PagefileUsage - end - end - else - PAT = /^\s*(\d+)\s+(\d+)$/ - require_relative 'find_executable' - if PSCMD = EnvUtil.find_executable("ps", "-ovsz=", "-orss=", "-p", $$.to_s) {|out| PAT =~ out} - PSCMD.pop - end - raise MiniTest::Skip, "ps command not found" unless PSCMD - - keys << :size << :rss - def self.read_status - if PAT =~ IO.popen(PSCMD + [$$.to_s], "r", err: [:child, :out], &:read) - yield :size, $1.to_i*1024 - yield :rss, $2.to_i*1024 - end - end - end - - Status = Struct.new(*keys) - - class Status - def _update - Memory.read_status do |key, val| - self[key] = val - end - end - end - - class Status - Header = members.map {|k| k.to_s.upcase.rjust(6)}.join('') - Format = "%6d" - - def initialize - _update - end - - def to_s - status = each_pair.map {|n,v| - "#{n}:#{v}" - } - "{#{status.join(",")}}" - end - - def self.parse(str) - status = allocate - str.scan(/(?:\A\{|\G,)(#{members.join('|')}):(\d+)(?=,|\}\z)/) do - status[$1] = $2.to_i - end - status - end - end -end -- cgit v1.2.3