summaryrefslogtreecommitdiff
path: root/test/fiber/test_io_close.rb
blob: 742b40841d90d685f0f2a336f2b5ccfbf9b802b9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# frozen_string_literal: true
require 'test/unit'
require_relative 'scheduler'

class TestFiberIOClose < Test::Unit::TestCase
  def with_socket_pair(&block)
    omit "UNIXSocket is not defined!" unless defined?(UNIXSocket)

    UNIXSocket.pair do |i, o|
      if RUBY_PLATFORM =~ /mswin|mingw/
        i.nonblock = true
        o.nonblock = true
      end

      yield i, o
    end
  end

  def test_io_close_across_fibers
    # omit "Interrupting a io_wait read is not supported!" if RUBY_PLATFORM =~ /mswin|mingw/

    with_socket_pair do |i, o|
      error = nil

      thread = Thread.new do
        scheduler = Scheduler.new
        Fiber.set_scheduler scheduler

        Fiber.schedule do
          i.read
        rescue => error
          # Ignore.
        end

        Fiber.schedule do
          i.close
        end
      end

      thread.join

      assert_instance_of IOError, error
      assert_match(/closed/, error.message)
    end
  end

  def test_io_close_blocking_thread
    omit "Interrupting a io_wait read is not supported!" if RUBY_PLATFORM =~ /mswin|mingw/

    with_socket_pair do |i, o|
      error = nil

      reading_thread = Thread.new do
        i.read
      rescue => error
        # Ignore.
      end

      Thread.pass until reading_thread.status == 'sleep'

      thread = Thread.new do
        scheduler = Scheduler.new
        Fiber.set_scheduler scheduler

        Fiber.schedule do
          i.close
        end
      end

      thread.join
      reading_thread.join

      assert_instance_of IOError, error
      assert_match(/closed/, error.message)
    end
  end

  def test_io_close_blocking_fiber
    # omit "Interrupting a io_wait read is not supported!" if RUBY_PLATFORM =~ /mswin|mingw/

    with_socket_pair do |i, o|
      error = nil

      thread = Thread.new do
        scheduler = Scheduler.new
        Fiber.set_scheduler scheduler

        Fiber.schedule do
          begin
            i.read
          rescue => error
            # Ignore.
          end
        end
      end

      Thread.pass until thread.status == 'sleep'

      i.close

      thread.join

      assert_instance_of IOError, error
      assert_match(/closed/, error.message)
    end
  end
end