Repository navigation
Expand file tree
/
Copy pathTestManagedProcess.hs
More file actions
382 lines (351 loc) · 15.9 KB
/
Copy pathTestManagedProcess.hs
File metadata and controls
382 lines (351 loc) · 15.9 KB
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
{-# LANGUAGE CPP #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE RecordWildCards #-}
module Main where
import Control.Concurrent.STM (atomically)
import Control.Concurrent.STM.TQueue
( newTQueueIO
, readTQueue
, writeTQueue
)
import Control.Concurrent.MVar
import Control.Exception (SomeException)
import Control.Distributed.Process hiding (call, catch)
import Control.Distributed.Process.Async (AsyncResult(AsyncDone))
import Control.Distributed.Process.Node
import Control.Distributed.Process.Extras hiding (monitor, send, nsend)
import Control.Distributed.Process.ManagedProcess
import Control.Distributed.Process.SysTest.Utils
import Control.Distributed.Process.Extras.Time
import Control.Distributed.Process.Serializable()
import Control.Monad (replicateM_)
import MathsDemo
import Counter
import qualified SafeCounter as SafeCounter
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.HUnit (testCase)
import TestUtils
import ManagedProcessCommon
import qualified Network.Transport as NT
import Control.Monad (void)
import Control.Monad.Catch (catch)
-- utilities
server :: Process (ProcessId, MVar ExitReason)
server = mkServer Terminate
mkServer :: UnhandledMessagePolicy
-> Process (ProcessId, MVar ExitReason)
mkServer policy =
let s = standardTestServer policy
in do
exitReason <- liftIO newEmptyMVar
pid <- spawnLocal $
catch ((serve () (statelessInit Infinity) s >> stash exitReason ExitNormal)
`catchesExit` [
(\_ msg -> do
mEx <- unwrapMessage msg :: Process (Maybe ExitReason)
case mEx of
Nothing -> return Nothing
Just r -> fmap Just (stash exitReason r)
)
])
(\(e :: SomeException) -> stash exitReason $ ExitOther (show e))
return (pid, exitReason)
explodingServer :: ProcessId
-> Process (ProcessId, MVar ExitReason)
explodingServer pid =
let srv = explodingTestProcess pid
in do
exitReason <- liftIO newEmptyMVar
spid <- spawnLocal $
catch (serve () (statelessInit Infinity) srv >> stash exitReason ExitNormal)
(\(e :: SomeException) -> stash exitReason $ ExitOther (show e))
return (spid, exitReason)
testCallReturnTypeMismatchHandling :: TestResult Bool -> Process ()
testCallReturnTypeMismatchHandling result =
let procDef = statelessProcess {
apiHandlers = [
handleCall (\s (m :: String) -> reply m s)
]
, unhandledMessagePolicy = Terminate
} in do
pid <- spawnLocal $ serve () (statelessInit Infinity) procDef
res <- safeCall pid "hello buddy" :: Process (Either ExitReason ())
case res of
Left (ExitOther _) -> stash result True
_ -> stash result False
testChannelBasedService :: TestResult Bool -> Process ()
testChannelBasedService result =
let procDef = statelessProcess {
apiHandlers = [
handleRpcChan (\p s (m :: String) ->
replyChan p m >> continue s)
]
} in do
pid <- spawnLocal $ serve () (statelessInit Infinity) procDef
echo <- syncCallChan pid "hello"
stash result (echo == "hello")
kill pid "done"
testExternalService :: TestResult Bool -> Process ()
testExternalService result = do
inChan <- liftIO newTQueueIO
replyQ <- liftIO newTQueueIO
let procDef = statelessProcess {
externHandlers = [
handleExternal
(readTQueue inChan)
(\s (m :: String) -> do
liftIO $ atomically $ writeTQueue replyQ m
continue s)
]
}
let txt = "hello 2-way stm foo"
pid <- spawnLocal $ serve () (statelessInit Infinity) procDef
echoTxt <- liftIO $ do
-- firstly we write something that the server can receive
atomically $ writeTQueue inChan txt
-- then sit and wait for it to write something back to us
atomically $ readTQueue replyQ
stash result (echoTxt == txt)
kill pid "done"
testExternalCall :: TestResult Bool -> Process ()
testExternalCall result = do
let txt = "hello stm-call foo"
srv <- launchEchoServer (\st (msg :: String) -> reply msg st)
echoStm srv txt >>= stash result . (== Right txt)
killProc srv "done"
testExternalCallHaltingServer :: TestResult Bool -> Process ()
testExternalCallHaltingServer result = do
let msg = "foo bar baz"
srv <- launchEchoServer (\_ (_ :: String) -> haltNoReply_ ExitNormal)
echoReply <- echoStm srv msg
case echoReply of
-- sadly, we cannot guarantee that our monitor will be set up fast
-- enough, as per the documentation!
Left (ExitOther reason) -> stash result $ reason `elem` [ "DiedUnknownId"
, "DiedNormal"
]
(Left ExitNormal) -> stash result False
(Left ExitShutdown) -> stash result False
(Right _) -> stash result False
-- MathDemo tests
testAdd :: TestResult Double -> Process ()
testAdd result = do
pid <- launchMathServer
add pid 10 10 >>= stash result
kill pid "done"
testBadAdd :: TestResult Bool -> Process ()
testBadAdd result = do
pid <- launchMathServer
res <- safeCall pid (Add 10 10) :: Process (Either ExitReason Int)
stash result (res == (Left $ ExitOther $ "DiedException \"exit-from=" ++ (show pid) ++ "\""))
testDivByZero :: TestResult (Either DivByZero Double) -> Process ()
testDivByZero result = do
pid <- launchMathServer
divide pid 125 0 >>= stash result
kill pid "done"
-- SafeCounter tests
testSafeCounterCurrentState :: ProcessId -> TestResult Int -> Process ()
testSafeCounterCurrentState pid result =
SafeCounter.getCount pid >>= stash result
testSafeCounterIncrement :: ProcessId -> TestResult Int -> Process ()
testSafeCounterIncrement pid result = do
5 <- SafeCounter.getCount pid
SafeCounter.resetCount pid
1 <- SafeCounter.incCount pid
2 <- SafeCounter.incCount pid
SafeCounter.getCount pid >>= stash result
-- Counter tests
testCounterCurrentState :: TestResult Int -> Process ()
testCounterCurrentState result = do
pid <- Counter.startCounter 5
getCount pid >>= stash result
testCounterIncrement :: TestResult Bool -> Process ()
testCounterIncrement result = do
pid <- Counter.startCounter 1
n <- getCount pid
2 <- incCount pid
3 <- incCount pid
getCount pid >>= \n' -> stash result (n' == (n + 2))
testCounterExceedsLimit :: TestResult Bool -> Process ()
testCounterExceedsLimit result = do
pid <- Counter.startCounter 1
mref <- monitor pid
-- exceed the limit
9 `replicateM_` (void $ incCount pid)
-- this time we should fail
_ <- (incCount pid)
`catchExit` \_ (_ :: ExitReason) -> return 0
r <- receiveWait [
matchIf (\(ProcessMonitorNotification ref _ _) -> ref == mref)
(\(ProcessMonitorNotification _ _ r') -> return r')
]
stash result (r /= DiedNormal)
tests :: NT.Transport -> IO TestTree
tests transport = do
localNode <- newLocalNode transport
scpid <- newEmptyMVar
_ <- forkProcess localNode $ SafeCounter.startCounter 5 >>= stash scpid
safeCounter <- takeMVar scpid
return $
testGroup "" [
testGroup "Basic Client/Server Functionality" [
testCase "basic call with explicit server reply"
(delayedAssertion
"expected a response from the server"
localNode (Just "foo") (testBasicCall $ wrap server))
, testCase "basic (unsafe) call with explicit server reply"
(delayedAssertion
"expected a response from the server"
localNode (Just "foo") (testUnsafeBasicCall $ wrap server))
, testCase "basic call with implicit server reply"
(delayedAssertion
"expected n * 2 back from the server"
localNode (Just 4) (testBasicCall_ $ wrap server))
, testCase "basic (unsafe) call with implicit server reply"
(delayedAssertion
"expected n * 2 back from the server"
localNode (Just 4) (testUnsafeBasicCall_ $ wrap server))
, testCase "basic deferred call handling"
(delayedAssertion "expected a response sent via replyTo"
localNode (AsyncDone "Hello There") testDeferredCallResponse)
, testCase "basic cast with manual send and explicit server continue"
(delayedAssertion
"expected pong back from the server"
localNode (Just "pong") (testBasicCast $ wrap server))
, testCase "basic (unsafe) cast with manual send and explicit server continue"
(delayedAssertion
"expected pong back from the server"
localNode (Just "pong") (testUnsafeBasicCast $ wrap server))
, testCase "basic channel based rpc"
(delayedAssertion
"expected response back from the server"
localNode True testChannelBasedService)
]
, testGroup "Unhandled Message Policies" [
testCase "unhandled input when policy = Terminate"
(delayedAssertion
"expected the server to stop upon receiving unhandled input"
localNode (Just $ ExitOther "UnhandledInput")
(testTerminatePolicy $ wrap server))
, testCase "(unsafe) unhandled input when policy = Terminate"
(delayedAssertion
"expected the server to stop upon receiving unhandled input"
localNode (Just $ ExitOther "UnhandledInput")
(testUnsafeTerminatePolicy $ wrap server))
, testCase "unhandled input when policy = Drop"
(delayedAssertion
"expected the server to ignore unhandled input and exit normally"
localNode Nothing (testDropPolicy $ wrap (mkServer Drop)))
, testCase "(unsafe) unhandled input when policy = Drop"
(delayedAssertion
"expected the server to ignore unhandled input and exit normally"
localNode Nothing (testUnsafeDropPolicy $ wrap (mkServer Drop)))
, testCase "unhandled input when policy = DeadLetter"
(delayedAssertion
"expected the server to forward unhandled messages"
localNode (Just ("UNSOLICITED_MAIL", 500 :: Int))
(testDeadLetterPolicy $ \p -> mkServer (DeadLetter p)))
, testCase "(unsafe) unhandled input when policy = DeadLetter"
(delayedAssertion
"expected the server to forward unhandled messages"
localNode (Just ("UNSOLICITED_MAIL", 500 :: Int))
(testUnsafeDeadLetterPolicy $ \p -> mkServer (DeadLetter p)))
, testCase "incoming messages are ignored whilst hibernating"
(delayedAssertion
"expected the server to remain in hibernation"
localNode True (testHibernation $ wrap server))
, testCase "(unsafe) incoming messages are ignored whilst hibernating"
(delayedAssertion
"expected the server to remain in hibernation"
localNode True (testUnsafeHibernation $ wrap server))
]
, testGroup "Server Exit Handling" [
testCase "simple exit handling"
(delayedAssertion "expected handler to catch exception and continue"
localNode Nothing (testSimpleErrorHandling $ explodingServer))
, testCase "(unsafe) simple exit handling"
(delayedAssertion "expected handler to catch exception and continue"
localNode Nothing (testUnsafeSimpleErrorHandling $ explodingServer))
, testCase "alternative exit handlers"
(delayedAssertion "expected handler to catch exception and continue"
localNode Nothing (testAlternativeErrorHandling $ explodingServer))
, testCase "(unsafe) alternative exit handlers"
(delayedAssertion "expected handler to catch exception and continue"
localNode Nothing (testUnsafeAlternativeErrorHandling $ explodingServer))
]
, testGroup "Advanced Server Interactions" [
testCase "taking arbitrary STM actions"
(delayedAssertion
"expected the server to read the STM queue and reply using STM"
localNode True testExternalService)
, testCase "using callSTM to manage non-CH interactions"
(delayedAssertion
"expected the server to reply back via the TQueue"
localNode True testExternalCall)
, testCase "getting error data back from callSTM"
(delayedAssertion
"expected the server to exit with ExitNormal"
localNode True testExternalCallHaltingServer)
, testCase "long running call cancellation"
(delayedAssertion "expected to get AsyncCancelled"
localNode True (testKillMidCall $ wrap server))
, testCase "(unsafe) long running call cancellation"
(delayedAssertion "expected to get AsyncCancelled"
localNode True (testUnsafeKillMidCall $ wrap server))
, testCase "server rejects call"
(delayedAssertion "expected server to send CallRejected"
localNode (ExitOther "invalid-call") (testServerRejectsMessage $ wrap server))
, testCase "invalid return type handling"
(delayedAssertion
"expected response to fail on runtime type verification"
localNode True testCallReturnTypeMismatchHandling)
, testCase "cast and explicit server timeout"
(delayedAssertion
"expected the server to stop after the timeout"
localNode (Just $ ExitOther "timeout") (testControlledTimeout $ wrap server))
, testCase "(unsafe) cast and explicit server timeout"
(delayedAssertion
"expected the server to stop after the timeout"
localNode (Just $ ExitOther "timeout") (testUnsafeControlledTimeout $ wrap server))
]
, testGroup "math server examples" [
testCase "error (Left) returned from x / 0"
(delayedAssertion
"expected the server to return DivByZero"
localNode (Left DivByZero) testDivByZero)
, testCase "10 + 10 = 20"
(delayedAssertion
"expected the server to return DivByZero"
localNode 20 testAdd)
, testCase "10 + 10 does not evaluate to 10 :: Int at all!"
(delayedAssertion
"expected the server to return ExitOther..."
localNode True testBadAdd)
]
, testGroup "counter server examples" [
testCase "initial counter state = 5"
(delayedAssertion
"expected the server to return the initial state of 5"
localNode 5 testCounterCurrentState)
, testCase "increment counter twice"
(delayedAssertion
"expected the server to return the incremented state as 7"
localNode True testCounterIncrement)
, testCase "exceed counter limits"
(delayedAssertion
"expected the server to terminate once the limit was exceeded"
localNode True testCounterExceedsLimit)
]
, testGroup "safe counter examples" [
testCase "initial counter state = 5"
(delayedAssertion
"expected the server to return the initial state of 5"
localNode 5 (testSafeCounterCurrentState safeCounter))
, testCase "increment counter twice"
(delayedAssertion
"expected the server to return the incremented state as 7"
localNode 2 (testSafeCounterIncrement safeCounter))
]
]
main :: IO ()
main = testMain $ tests