1 {-# LANGUAGE OverloadedStrings #-}
2 {-# LANGUAGE RankNTypes #-}
3 {-# LANGUAGE ScopedTypeVariables #-}
4 {-# LANGUAGE ExistentialQuantification #-}
7 -- Module : Language.Haskell.LSP.Test
8 -- Description : A functional testing framework for LSP servers.
9 -- Maintainer : luke_lau@icloud.com
10 -- Stability : experimental
12 -- A framework for testing <https://github.com/Microsoft/language-server-protocol Language Server Protocol servers> at the JSON level.
14 module Language.Haskell.LSP.Test
29 import Control.Monad.Trans.Class
30 import Control.Monad.IO.Class
31 import Control.Monad.Trans.Reader
32 import Control.Monad.Trans.State
33 import Control.Concurrent
34 import qualified Data.Text as T
35 import qualified Data.Text.IO as T
37 import qualified Data.ByteString.Lazy.Char8 as B
42 import Language.Haskell.LSP.Types hiding (error, id)
45 import System.Directory
46 import System.FilePath
47 import Language.Haskell.LSP.Test.Parsing
49 data SessionContext = SessionContext
51 messageSema :: MVar B.ByteString,
57 newtype SessionState = SessionState
62 -- | A session representing one instance of launching and connecting to a server.
64 -- You can send and receive messages to the server within 'Session' via 'getMessage',
65 -- 'sendRequest' and 'sendNotification'.
68 -- runSession \"path\/to\/root\/dir\" $ do
69 -- docItem <- getDocItem "Desktop/simple.hs" "haskell"
70 -- sendNotification TextDocumentDidOpen (DidOpenTextDocumentParams docItem)
71 -- diagnostics <- getMessage :: Session PublishDiagnosticsNotification
74 type Session = StateT SessionState (ReaderT SessionContext IO)
76 -- | Starts a new session.
77 runSession :: FilePath -- ^ The filepath to the root directory for the session.
78 -> Session a -- ^ The session to run.
80 runSession rootDir session = do
82 absRootDir <- canonicalizePath rootDir
84 (Just serverIn, Just serverOut, Nothing, serverProc) <- createProcess
85 (proc "hie" ["--lsp", "-d", "-l", "/tmp/hie-test.log"])
86 { std_in = CreatePipe, std_out = CreatePipe }
88 hSetBuffering serverIn NoBuffering
89 hSetBuffering serverOut NoBuffering
92 messageSema <- newEmptyMVar
94 let initializeParams :: InitializeParams
95 initializeParams = InitializeParams (Just pid)
96 (Just $ T.pack absRootDir)
97 (Just $ filePathToUri absRootDir)
101 context = SessionContext messageSema serverIn serverOut absRootDir
102 initState = SessionState (IdInt 9)
104 -- | The session wrapped around initialize and shutdown calls
106 sendRequest (Proxy :: Proxy InitializeRequest) Initialize initializeParams
107 (ResponseMessage _ _ (Just (InitializeResponseCapabilities _)) e) <- getMessage
108 liftIO $ maybe (return ()) (putStrLn . ("Error when initializing: " ++) . show ) e
110 sendNotification Initialized InitializedParams
112 -- Run the actual test
115 sendNotification Exit ExitParams
117 forkIO $ listenServer context
118 _ <- runReaderT (runStateT fullSession initState) context
120 terminateProcess serverProc
124 -- | Listens to the server output, makes sure it matches the record and
125 -- signals any semaphores
126 listenServer :: SessionContext -> IO ()
127 listenServer context = do
128 msgBytes <- getNextMessage (serverOut context)
130 case decode msgBytes :: Maybe LogMessageNotification of
131 -- Just print log and show messages
132 Just (NotificationMessage _ WindowLogMessage (LogMessageParams _ msg)) -> T.putStrLn msg
133 _ -> case decode msgBytes :: Maybe ShowMessageNotification of
134 Just (NotificationMessage _ WindowShowMessage (ShowMessageParams _ msg)) -> T.putStrLn msg
135 -- Give everything else for getMessage to handle
136 _ -> putMVar (messageSema context) msgBytes
140 -- | Sends a request to the server.
143 -- sendRequest (Proxy :: Proxy DocumentSymbolRequest)
144 -- TextDocumentDocumentSymbol
145 -- (DocumentSymbolParams docId)
148 :: forall params resp. (ToJSON params, ToJSON resp, FromJSON resp)
149 => Proxy (RequestMessage ClientMethod params resp) -- ^ A proxy to provide more type information about the request.
150 -> ClientMethod -- ^ The request method.
151 -> params -- ^ The request parameters.
152 -> Session LspId -- ^ The id of the request that was sent.
153 sendRequest _ method params = do
154 h <- serverIn <$> lift ask
156 id <- curReqId <$> get
157 get >>= \c -> put c { curReqId = nextId id }
159 let msg = RequestMessage "2.0" id method params :: RequestMessage ClientMethod params resp
161 liftIO $ B.hPut h $ addHeader (encode msg)
165 where nextId (IdInt i) = IdInt (i + 1)
166 nextId (IdString s) = IdString $ T.pack $ show $ read (T.unpack s) + 1
168 -- | Sends a notification to the server.
169 sendNotification :: ToJSON a
170 => ClientMethod -- ^ The notification method.
171 -> a -- ^ The notification parameters.
173 sendNotification method params = do
174 h <- serverIn <$> lift ask
176 let msg = NotificationMessage "2.0" method params
177 liftIO $ B.hPut h $ addHeader (encode msg)
179 -- | Reads in a message from the server.
180 getMessage :: FromJSON a => Session a
182 sema <- messageSema <$> lift ask
183 bytes <- liftIO $ takeMVar sema
184 return $ fromMaybe (error $ "Wrong type! Got: " ++ show bytes) (decode bytes)
186 -- | Reads in a text document as the first version.
187 getDocItem :: FilePath -- ^ The path to the text document to read in.
188 -> String -- ^ The language ID, e.g "haskell" for .hs files.
189 -> Session TextDocumentItem
190 getDocItem file languageId = do
192 let fp = rootDir context </> file
193 contents <- liftIO $ T.readFile fp
194 return $ TextDocumentItem (filePathToUri fp) (T.pack languageId) 0 contents
196 -- | Gets the Uri for the file corrected to the session directory.
197 getDocUri :: FilePath -> Session Uri
200 let fp = rootDir context </> file
201 return $ filePathToUri fp