1 {-# LANGUAGE OverloadedStrings #-}
2 {-# LANGUAGE FlexibleContexts #-}
3 -- | A testing tool for replaying recorded client logs back to a server,
4 -- and validating that the server output matches up with another log.
5 module Language.Haskell.LSP.Test.Recorded
10 import Control.Concurrent
11 import Control.Monad.Trans.Class
12 import Control.Monad.Trans.Reader
14 import Language.Haskell.LSP.Control as Control
15 import qualified Data.ByteString.Lazy.Char8 as B
16 import Language.Haskell.LSP.Core
17 import qualified Language.Haskell.LSP.Types as LSP
23 import System.Directory
25 import Language.Haskell.LSP.Test.Files
26 import Language.Haskell.LSP.Test.Parsing
28 -- | Replays a recorded client output and
29 -- makes sure it matches up with an expected response.
31 :: FilePath -- ^ The client output to replay to the server.
32 -> FilePath -- ^ The expected response from the server.
33 -> FilePath -- ^ The root directory of the project
35 replay cfp sfp curRootDir = do
37 -- need to keep hold of current directory since haskell-lsp changes it
38 prevDir <- getCurrentDirectory
40 (Just serverIn, Just serverOut, _, serverProc) <- createProcess
41 (proc "hie" ["--lsp", "-l", "/tmp/hie.log"]) { std_in = CreatePipe , std_out = CreatePipe }
43 hSetBuffering serverIn NoBuffering
44 hSetBuffering serverOut NoBuffering
46 -- whether to send the next request
47 reqSema <- newEmptyMVar :: IO (MVar LSP.LspIdRsp)
48 -- whether to send the next response
49 rspSema <- newEmptyMVar :: IO (MVar LSP.LspId)
50 let semas = (reqSema, rspSema)
52 didPass <- newEmptyMVar
54 -- the recorded client input to the server
55 clientRecIn <- openFile cfp ReadMode
56 serverRecIn <- openFile sfp ReadMode
57 null <- openFile "/dev/null" WriteMode
60 unswappedClientMsgs <- getAllMessages clientRecIn
62 let recRootDir = rootDir unswappedClientMsgs
64 (clientMsgs, fileMap) <- swapFiles emptyFileMap recRootDir curRootDir unswappedClientMsgs
66 tmpDir <- getTemporaryDirectory
67 (mappedClientRecFp, mappedClientRecIn) <- openTempFile tmpDir "clientRecInMapped"
68 mapM_ (B.hPut mappedClientRecIn . addHeader) clientMsgs
69 hSeek mappedClientRecIn AbsoluteSeek 0
71 (expectedMsgs, _) <- swapFiles fileMap recRootDir curRootDir =<< getAllMessages serverRecIn
74 forkIO $ runReaderT (listenServer expectedMsgs serverOut semas) didPass
76 -- start client replay
78 Control.runWithHandles mappedClientRecIn
80 (const $ Right (), const $ return Nothing)
81 (handlers serverIn semas)
86 -- todo: we shouldn't do this, we should check all notifications were delivered first
89 result <- takeMVar didPass
90 terminateProcess serverProc
93 setCurrentDirectory prevDir
96 removeFile mappedClientRecFp
100 -- | The internal monad for tests that can fail or pass,
101 -- ending execution early.
102 type Session = ReaderT (MVar Bool) IO
104 failSession :: String -> Session ()
105 failSession reason = do
106 lift $ putStrLn reason
108 lift $ putMVar passVar False
110 passSession :: Session ()
113 lift $ putMVar passVar True
115 -- | Listens to the server output, makes sure it matches the record and
116 -- signals any semaphores
117 listenServer :: [B.ByteString] -> Handle -> (MVar LSP.LspIdRsp, MVar LSP.LspId) -> Session ()
118 listenServer [] _ _ = passSession
119 listenServer expectedMsgs h semas@(reqSema, rspSema) = do
120 msg <- lift $ getNextMessage h
122 newExpectedMsgs <- case decode msg of
124 Nothing -> case decode msg of
125 Just m -> notification m
126 Nothing -> case decode msg of
128 Nothing -> failSession "Malformed message" >> return expectedMsgs
130 listenServer newExpectedMsgs h semas
133 where response :: LSP.ResponseMessage Value -> Session [B.ByteString]
135 lift $ putStrLn $ "Got response for id " ++ show (res ^. LSP.id)
141 lift $ putMVar reqSema (res ^. LSP.id) -- unblock the handler waiting to send a request
145 request :: LSP.RequestMessage LSP.ServerMethod Value Value -> Session [B.ByteString]
147 lift $ putStrLn $ "Got request for id " ++ show (req ^. LSP.id) ++ " " ++ show (req ^. LSP.method)
153 lift $ putMVar rspSema (req ^. LSP.id) -- unblock the handler waiting for a response
157 notification :: LSP.NotificationMessage LSP.ServerMethod Value -> Session [B.ByteString]
159 lift $ putStrLn $ "Got notification " ++ show (n ^. LSP.method)
162 lift $ putStrLn $ show ((length $ filter isNotification expectedMsgs) - 1) ++ " notifications remaining"
164 if n ^. LSP.method == LSP.WindowLogMessage
165 then return expectedMsgs
168 checkOrder msg = unless (inRightOrder msg expectedMsgs) $ do
169 let (Just expected) = decode firstExpected
170 _ = expected == msg -- make expected type same as res
171 failSession ("Out of order\nExpected\n" ++ show expected ++ "\nGot\n" ++ show msg ++ "\n")
174 let new = deleteFirstJson msg expectedMsgs
175 in if new == expectedMsgs
176 then failSession ("Unexpected message: " ++ show msg) >> return new
179 deleteFirstJson _ [] = []
180 deleteFirstJson msg (x:xs)
181 | Just msg == decode x = xs
182 | otherwise = x:deleteFirstJson msg xs
184 firstExpected = head $ filter (not . isNotification) expectedMsgs
188 isNotification :: B.ByteString -> Bool
190 isJust (decode msg :: Maybe (LSP.NotificationMessage Value Value))
192 -- TODO: QuickCheck tests?
193 -- | Checks wether or not the message appears in the right order
194 -- @ N1 N2 N3 REQ1 N4 N5 REQ2 RES1 @
195 -- given N2, notification order doesn't matter.
196 -- @ N1 N3 REQ1 N4 N5 REQ2 RES1 @
198 -- @ N1 N3 N4 N5 REQ2 RES1 @
200 -- @ N1 N3 N4 N5 XXXX RES1 @ False!
201 -- Order of requests and responses matter
202 inRightOrder :: (FromJSON a, Eq a) => a -> [B.ByteString] -> Bool
204 inRightOrder _ [] = error "Why is this empty"
205 -- inRightOrder (LSP.NotificationMessage _ _ _) _ = True
207 inRightOrder received (expected:msgs)
208 | Just received == decode expected = True
209 | isNotification expected = inRightOrder received msgs
213 handlers :: Handle -> (MVar LSP.LspIdRsp, MVar LSP.LspId) -> Handlers
214 handlers serverH (reqSema, rspSema) = def
217 hoverHandler = Just request
218 , completionHandler = Just request
219 , completionResolveHandler = Just request
220 , signatureHelpHandler = Just request
221 , definitionHandler = Just request
222 , referencesHandler = Just request
223 , documentHighlightHandler = Just request
224 , documentSymbolHandler = Just request
225 , workspaceSymbolHandler = Just request
226 , codeActionHandler = Just request
227 , codeLensHandler = Just request
228 , codeLensResolveHandler = Just request
229 , documentFormattingHandler = Just request
230 , documentRangeFormattingHandler = Just request
231 , documentTypeFormattingHandler = Just request
232 , renameHandler = Just request
233 , documentLinkHandler = Just request
234 , documentLinkResolveHandler = Just request
235 , executeCommandHandler = Just request
236 , initializeRequestHandler = Just request
238 , didChangeConfigurationParamsHandler = Just notification
239 , didOpenTextDocumentNotificationHandler = Just notification
240 , didChangeTextDocumentNotificationHandler = Just notification
241 , didCloseTextDocumentNotificationHandler = Just notification
242 , didSaveTextDocumentNotificationHandler = Just notification
243 , didChangeWatchedFilesNotificationHandler = Just notification
244 , initializedHandler = Just notification
245 , willSaveTextDocumentNotificationHandler = Just notification
246 , cancelNotificationHandler = Just notification
247 , exitNotificationHandler = Just notification
249 , responseHandler = Just response
253 -- TODO: May need to prevent premature exit notification being sent
254 notification msg@(LSP.NotificationMessage _ LSP.Exit _) = do
255 putStrLn "Will send exit notification soon"
257 B.hPut serverH $ addHeader (encode msg)
258 notification msg@(LSP.NotificationMessage _ m _) = do
259 B.hPut serverH $ addHeader (encode msg)
261 putStrLn $ "Sent a notification " ++ show m
263 request msg@(LSP.RequestMessage _ id m _) = do
265 when (m == LSP.TextDocumentDocumentSymbol) $ threadDelay 5000000
267 B.hPut serverH $ addHeader (encode msg)
268 putStrLn $ "Sent a request id " ++ show id ++ ": " ++ show m ++ "\nWaiting for a response"
270 rspId <- takeMVar reqSema
271 when (LSP.responseId id /= rspId)
278 response msg@(LSP.ResponseMessage _ id _ _) = do
279 putStrLn $ "Waiting for request id " ++ show id ++ " from the server"
280 reqId <- takeMVar rspSema
281 if LSP.responseId reqId /= id
282 then error $ "Expected id " ++ show reqId ++ ", got " ++ show reqId
284 B.hPut serverH $ addHeader (encode msg)
285 putStrLn $ "Sent response to request id " ++ show id