* 2022-01-18 [ci skip]
[ruby-80x24.org.git] / test / ruby / test_readpartial.rb
blobbc22556cd4e9e38ac6095712d6fb04a09848b028
1 # frozen_string_literal: false
2 require 'test/unit'
3 require 'timeout'
4 require 'fcntl'
6 class TestReadPartial < Test::Unit::TestCase
7   def make_pipe
8     r, w = IO.pipe
9     r.binmode
10     w.binmode
11     begin
12       yield r, w
13     ensure
14       r.close unless r.closed?
15       w.close unless w.closed?
16     end
17   end
19   def pipe
20     make_pipe {|r, w|
21       yield r, w
22     }
23     return unless defined?(Fcntl::F_SETFL)
24     return unless defined?(Fcntl::F_GETFL)
25     return unless defined?(Fcntl::O_NONBLOCK)
26     make_pipe {|r, w|
27       r.fcntl(Fcntl::F_SETFL, r.fcntl(Fcntl::F_GETFL) | Fcntl::O_NONBLOCK)
28       yield r, w
29     }
30   end
32   def test_length_zero
33     pipe {|r, w|
34       assert_equal('', r.readpartial(0))
35     }
36   end
38   def test_closed_pipe
39     pipe {|r, w|
40       w << 'abc'
41       w.close
42       assert_equal('ab', r.readpartial(2))
43       assert_equal('c', r.readpartial(2))
44       assert_raise(EOFError) { r.readpartial(2) }
45       assert_raise(EOFError) { r.readpartial(2) }
46     }
47   end
49   def test_open_pipe
50     pipe {|r, w|
51       w << 'abc'
52       assert_equal('ab', r.readpartial(2))
53       assert_equal('c', r.readpartial(2))
54       assert_raise(Timeout::Error) {
55         Timeout.timeout(0.1) { r.readpartial(2) }
56       }
57     }
58   end
60   def test_with_stdio
61     pipe {|r, w|
62       w << "abc\ndef\n"
63       assert_equal("abc\n", r.gets)
64       w << "ghi\n"
65       assert_equal("de", r.readpartial(2))
66       assert_equal("f\n", r.readpartial(4096))
67       assert_equal("ghi\n", r.readpartial(4096))
68       assert_raise(Timeout::Error) {
69         Timeout.timeout(0.1) { r.readpartial(2) }
70       }
71     }
72   end
73 end