5
# This testcase does NOT aim to test cryptographically strongness and randomness.
6
class TestSecureRandom < Test::Unit::TestCase
11
def test_s_random_bytes
12
assert_equal(16, @it.random_bytes.size)
13
assert_equal(Encoding::ASCII_8BIT, @it.random_bytes.encoding)
15
assert_equal(idx, @it.random_bytes(idx).size)
19
# This test took 2 minutes on my machine.
20
# And 65536 times loop could not be enough for forcing PID recycle.
22
def test_s_random_bytes_is_fork_safe
28
SecureRandom.random_bytes(8)
29
pid, v1 = forking_random_bytes
30
assert(check_forking_random_bytes(pid, v1), 'Process ID not recycled?')
33
def forking_random_bytes
37
w.write SecureRandom.random_bytes(8)
47
def check_forking_random_bytes(target_pid, target)
51
v2 = SecureRandom.random_bytes(8)
60
pid, status = Process.waitpid2(pid)
61
case status.exitstatus
63
raise 'returned same sequence for same PID'
72
def test_s_random_bytes_without_openssl
79
load_path = $LOAD_PATH.dup
80
loaded_features = $LOADED_FEATURES.dup
81
openssl = Object.instance_eval { remove_const(:OpenSSL) }
83
remove_feature('securerandom.rb')
84
remove_feature('openssl.rb')
86
open(File.join(dir, 'openssl.rb'), 'w') { |f|
87
f << 'raise LoadError'
89
$LOAD_PATH.unshift(dir)
90
require 'securerandom'
94
$LOADED_FEATURES.replace(loaded_features)
95
$LOAD_PATH.replace(load_path)
96
Object.const_set(:OpenSSL, openssl)
101
assert_equal(16 * 2, @it.hex.size)
103
assert_equal(idx * 2, @it.hex(idx).size)
104
assert_equal(idx, @it.hex(idx).gsub(/(..)/) { [$1].pack('H*') }.size)
109
assert_equal(16, @it.base64.unpack('m*')[0].size)
111
assert_equal(idx, @it.base64(idx).unpack('m*')[0].size)
115
def test_s_urlsafe_base64
118
assert_not_match(safe, @it.urlsafe_base64(idx))
120
# base64 can include unsafe byte
122
return if safe =~ @it.base64(idx)
127
def test_s_random_number_float
129
v = @it.random_number
130
assert(0.0 <= v && v < 1.0)
134
def test_s_random_number_float_by_zero
136
v = @it.random_number(0)
137
assert(0.0 <= v && v < 1.0)
141
def test_s_random_number_int
144
v = @it.random_number(idx)
145
assert(0 <= v && v < idx)
151
assert_equal(36, uuid.size)
152
uuid.unpack('a8xa4xa4xa4xa12').each do |e|
153
assert_match(/^[0-9a-f]+$/, e)
160
rescue NotImplementedError
165
def remove_feature(basename)
166
$LOADED_FEATURES.delete_if { |path|
167
if File.basename(path) == basename
168
$LOAD_PATH.any? { |dir|
169
File.exists?(File.join(dir, basename))