[rubygems/rubygems] Use a constant empty tar header to avoid extra allocations
[ruby.git] / test / test_securerandom.rb
blobe4a0e17365e55a14d019f3c720bc643474ddbd75
1 # frozen_string_literal: false
2 require 'test/unit'
3 require 'securerandom'
4 require_relative 'ruby/test_random_formatter'
6 # This testcase does NOT aim to test cryptographically strongness and randomness.
7 class TestSecureRandom < Test::Unit::TestCase
8   include Random::Formatter::FormatterTest
9   include Random::Formatter::NotDefaultTest
11   def setup
12     @it = SecureRandom
13   end
15 # This test took 2 minutes on my machine.
16 # And 65536 times loop could not be enough for forcing PID recycle.
17 if false
18   def test_s_random_bytes_is_fork_safe
19     begin
20       require 'openssl'
21     rescue LoadError
22       return
23     end
24     SecureRandom.random_bytes(8)
25     pid, v1 = forking_random_bytes
26     assert(check_forking_random_bytes(pid, v1), 'Process ID not recycled?')
27   end
29   def forking_random_bytes
30     r, w = IO.pipe
31     pid = fork {
32       r.close
33       w.write SecureRandom.random_bytes(8)
34       w.close
35     }
36     w.close
37     v = r.read(8)
38     r.close
39     Process.waitpid2(pid)
40     [pid, v]
41   end
43   def check_forking_random_bytes(target_pid, target)
44     65536.times do
45       pid = fork {
46         if $$ == target_pid
47           v2 = SecureRandom.random_bytes(8)
48           if v2 == target
49             exit(1)
50           else
51             exit(2)
52           end
53         end
54         exit(3)
55       }
56       pid, status = Process.waitpid2(pid)
57       case status.exitstatus
58       when 1
59         raise 'returned same sequence for same PID'
60       when 2
61         return true
62       end
63     end
64     false # not recycled?
65   end
66 end
68   def test_with_openssl
69     begin
70       require 'openssl'
71     rescue LoadError
72       return
73     end
74     assert_equal(Encoding::ASCII_8BIT, @it.send(:gen_random_openssl, 16).encoding)
75     65.times do |idx|
76       assert_equal(idx, @it.send(:gen_random_openssl, idx).size)
77     end
78   end
80   def test_repeated_gen_random
81     assert_nothing_raised NoMethodError, '[ruby-core:92633] [Bug #15847]' do
82       @it.gen_random(1)
83       @it.gen_random(1)
84     end
85   end
86 end