-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathasynchronousSpec.scala
75 lines (65 loc) · 2.01 KB
/
asynchronousSpec.scala
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
package com.thoughtworks.raii
import java.io.StringWriter
import com.thoughtworks.future._
import com.thoughtworks.raii.asynchronous._
import scalaz.syntax.all._
import org.scalatest.{Assertion, AsyncFreeSpec, FreeSpec, Matchers}
import scala.concurrent.Promise
import com.thoughtworks.raii.scalatest.ThoughtWorksFutureToScalaFuture
import scalaz.Trampoline
/**
* @author 杨博 (Yang Bo) <[email protected]>
*/
final class asynchronousSpec extends AsyncFreeSpec with Matchers with ThoughtWorksFutureToScalaFuture {
"Given a scoped resource" - {
var isSourceClosed = false
val source = Do.scoped(new AutoCloseable {
isSourceClosed should be(false)
override def close(): Unit = {
isSourceClosed should be(false)
isSourceClosed = true
}
})
"And flatMap the resource to an new autoReleaseDependencies resource" - {
var isResultClosed = false
val result = source.intransitiveFlatMap { sourceCloseable =>
Do.scoped(new AutoCloseable {
isResultClosed should be(false)
override def close(): Unit = {
isResultClosed should be(false)
isResultClosed = true
}
})
}
"When map the new resource" - {
"Then dependency resource should have been released" in {
val p = Promise[Assertion]
ThoughtworksFutureOps(result.map { r =>
isSourceClosed should be(true)
isResultClosed should be(false)
}.run)
.onComplete { either =>
isSourceClosed should be(true)
isResultClosed should be(true)
val _ = p.complete(either)
}
p.future
}
}
}
}
"Nested flatMaps should be stack-safe" in {
def loop(acc: Int, i: Int = 0): Do[Int] = {
if (i < 30000) {
Do.now(i).flatMap { i =>
loop(acc + i, i + 1)
}
} else {
Do.now(acc)
}
}
loop(0, 0).run.map { i =>
i should be((1 until 30000).sum)
}
}
}