aboutsummaryrefslogtreecommitdiff
path: root/stdlib/test/test/lux/concurrency/promise.lux
blob: 0aae405ab6b7d9774adb91b1351e86c194169678 (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
(.module:
  [lux #*
   [io (#+ IO io)]
   [control
    ["M" monad (#+ do Monad)]
    pipe]
   [data
    [number]
    [text
     format]]
   [concurrency
    ["&" promise ("&/" Monad<Promise>)]]
   [math
    ["r" random]]]
  lux/test)

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

      (wrap (do &.Monad<Promise>
              [_ (&.wait +500)]
              (assert "Can wait for a specified amount of time."
                      #1)))

      (wrap (do &.Monad<Promise>
              [[left right] (&.seq (&.future (io #1))
                                   (&.future (io #0)))]
              (assert "Can combine promises sequentially."
                      (and left (not right)))))

      (wrap (do &.Monad<Promise>
              [?left (&.alt (&.delay +100 #1)
                            (&.delay +200 #0))
               ?right (&.alt (&.delay +200 #1)
                             (&.delay +100 #0))]
              (assert "Can combine promises alternatively."
                      (case [?left ?right]
                        [(#.Left #1) (#.Right #0)]
                        #1

                        _
                        #0))))

      (wrap (do &.Monad<Promise>
              [?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))))

      (test "Cannot re-resolve a resolved promise."
            (and (not (io.run (&.resolve #0 (&/wrap #1))))
                 (io.run (&.resolve #1 (: (&.Promise Bit) (&.promise #.None))))))

      (wrap (do &.Monad<Promise>
              [?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))))
      ))