summaryrefslogtreecommitdiffhomepage
path: root/mrbgems/mruby-fiber/test/fiber.rb
blob: 62037289858542c26d7146db1426234e097b8e62 (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
108
109
110
111
112
assert('Fiber.new') {
  f = Fiber.new{}
  f.class == Fiber
}

assert('Fiber#resume') {
  f = Fiber.new{|x| x == 2}
  f.resume(2)
}

assert('Fiber#alive?') {
  f = Fiber.new{ Fiber.yield }
  f.resume
  r1 = f.alive?
  f.resume
  r2 = f.alive?
  r1 == true and r2 == false
}

assert('Fiber#==') do
  root = Fiber.current
  assert_equal root, root
  assert_equal root, Fiber.current
  assert_false root != Fiber.current
  f = Fiber.new {
    assert_false root == Fiber.current
  }
  f.resume
  assert_false f == root
  assert_true f != root
end

assert('Fiber.yield') {
  f = Fiber.new{|x| Fiber.yield(x == 3)}
  f.resume(3)
}

assert('FiberError') do
  assert_equal StandardError, FiberError.superclass
end

assert('Fiber iteration') {
  f1 = Fiber.new{
    [1,2,3].each{|x| Fiber.yield(x)}
  }
  f2 = Fiber.new{
    [9,8,7].each{|x| Fiber.yield(x)}
  }
  a = []
  3.times {
    a << f1.resume
    a << f2.resume
  }
  a == [1,9,2,8,3,7]
}

assert('Fiber with splat in the block argument list') {
  Fiber.new{|*x|x}.resume(1) == [1]
}

assert('Fiber raises on resume when dead') do
  assert_raise(FiberError) do
    f = Fiber.new{}
    f.resume
    assert_false f.alive?
    f.resume
  end
end

assert('Yield raises when called on root fiber') do
  assert_raise(FiberError) { Fiber.yield }
end

assert('Double resume of Fiber') do
  f1 = Fiber.new {}
  f2 = Fiber.new {
    f1.resume
    assert_raise(FiberError) { f2.resume }
    Fiber.yield 0
  }
  assert_equal 0, f2.resume
  f2.resume
  assert_false f1.alive?
  assert_false f2.alive?
end

assert('Recursive resume of Fiber') do
  f1, f2 = nil, nil
  f1 = Fiber.new { assert_raise(FiberError) { f2.resume } }
  f2 = Fiber.new {
    f1.resume
    Fiber.yield 0
  }
  f3 = Fiber.new {
    f2.resume
  }
  assert_equal 0, f3.resume
  f2.resume
  assert_false f1.alive?
  assert_false f2.alive?
  assert_false f3.alive?
end

assert('Root fiber resume') do
  root = Fiber.current
  assert_raise(FiberError) { root.resume }
  f = Fiber.new {
    assert_raise(FiberError) { root.resume }
  }
  f.resume
  assert_false f.alive?
end