aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/test/lux/control/concurrency/promise.lux
blob: 295c26e208bdcc9b7408c842a63c8f2e23f42a77 (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
(.module:
  [lux #*
   ["." io]
   [control
    ["M" monad (#+ Monad do)]
    pipe
    [concurrency
     ["&" promise ("&;." monad)]]]
   [math
    ["r" random]]]
  lux/test)

(context: "Promises"
  ($_ seq
      (wrap (do &.monad
              [running? (&.future (io.io #1))]
              (assert "Can run IO actions in separate threads."
                      running?)))

      (wrap (do &.monad
              [_ (&.wait 500)]
              (assert "Can wait for a specified amount of time."
                      #1)))

      (wrap (do &.monad
              [[left right] (&.and (&.future (io.io #1))
                                   (&.future (io.io #0)))]
              (assert "Can combine promises sequentially."
                      (and left (not right)))))

      (wrap (do &.monad
              [?left (&.or (&.delay 100 #1)
                           (&.delay 200 #0))
               ?right (&.or (&.delay 200 #1)
                            (&.delay 100 #0))]
              (assert "Can combine promises alternatively."
                      (case [?left ?right]
                        [(#.Left #1) (#.Right #0)]
                        #1

                        _
                        #0))))

      (wrap (do &.monad
              [?left (&.either (&.delay 100 #1)
                               (&.delay 200 #0))
               ?right (&.either (&.delay 200 #1)
                                (&.delay 100 #0))]
              (assert "Can combine promises alternatively [Part 2]."
                      (and ?left (not ?right)))))

      (test "Can poll a promise for its value."
            (and (|> (&.poll (&;wrap #1))
                     (case> (#.Some #1) #1 _ #0))
                 (|> (&.poll (&.delay 200 #1))
                     (case> #.None #1 _ #0))))

      (wrap (do &.monad
              [?none (&.time-out 100 (&.delay 200 #1))
               ?some (&.time-out 200 (&.delay 100 #1))]
              (assert "Can establish maximum waiting times for promises to be fulfilled."
                      (case [?none ?some]
                        [#.None (#.Some #1)]
                        #1

                        _
                        #0))))
      ))