This repository was archived by the owner on Oct 7, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 206
/
Copy pathTestUtils.hs
413 lines (357 loc) · 14.6 KB
/
TestUtils.hs
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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
{-# LANGUAGE CPP, OverloadedStrings, NamedFieldPuns #-}
module TestUtils
(
withFileLogging
, setupBuildToolFiles
, testCommand
, runSingle
, runSingle'
, runSingleReq
, makeRequest
, runIGM
, runIGM'
, ghcVersion, GhcVersion(..)
, logFilePath
, readResolver
, hieCommand
, hieCommandVomit
, hieCommandExamplePlugin
, getHspecFormattedConfig
, testOptions
, flushStackEnvironment
, dummyLspFuncs
) where
import Control.Concurrent.STM
import Control.Monad
import Data.Aeson.Types (typeMismatch)
import Data.Default
import Data.List (intercalate)
import Data.Text (pack)
import Data.Typeable
import Data.Yaml
import qualified Data.Map as Map
import Data.Maybe
import Language.Haskell.LSP.Core
import Language.Haskell.LSP.Types (LspId(IdInt), fromNormalizedUri)
import Haskell.Ide.Engine.MonadTypes hiding (withProgress, withIndefiniteProgress)
import qualified Haskell.Ide.Engine.Cradle as Bios
import qualified Haskell.Ide.Engine.Config as Config
import System.Directory
import System.Environment
import System.FilePath
import qualified System.Log.Logger as L
import Test.Hspec
import Test.Hspec.Runner
import Test.Hspec.Core.Formatters
import Text.Blaze.Renderer.String (renderMarkup)
import Text.Blaze.Internal
import qualified Haskell.Ide.Engine.PluginApi as HIE (BiosOptions, defaultOptions)
import HIE.Bios.Types
testOptions :: HIE.BiosOptions
testOptions = HIE.defaultOptions { cradleOptsVerbosity = Verbose }
-- ---------------------------------------------------------------------
testCommand :: (ToJSON a, Typeable b, ToJSON b, Show b, Eq b)
=> IdePlugins -> FilePath -> IdeGhcM (IdeResult b) -> PluginId -> CommandId -> a -> IdeResult b -> IO ()
testCommand testPlugins fp act plugin cmd arg res = do
flushStackEnvironment
(newApiRes, oldApiRes) <- runIGM testPlugins fp $ do
new <- act
old <- makeRequest plugin cmd arg
return (new, old)
newApiRes `shouldBe` res
fmap fromDynJSON oldApiRes `shouldBe` fmap Just res
runSingle :: IdePlugins -> FilePath -> IdeGhcM (IdeResult b) -> IO (IdeResult b)
runSingle = runSingle' id
runSingle' :: (Config.Config -> Config.Config) -> IdePlugins -> FilePath -> IdeGhcM (IdeResult b) -> IO (IdeResult b)
runSingle' modifyConfig testPlugins fp act = runIGM' modifyConfig testPlugins fp act
runSingleReq :: ToJSON a
=> IdePlugins -> FilePath -> PluginId -> CommandId -> a -> IO (IdeResult DynamicJSON)
runSingleReq testPlugins fp plugin com arg = runIGM testPlugins fp (makeRequest plugin com arg)
makeRequest :: ToJSON a => PluginId -> CommandId -> a -> IdeGhcM (IdeResult DynamicJSON)
makeRequest plugin com arg = runPluginCommand plugin com (toJSON arg)
runIGM :: IdePlugins -> FilePath -> IdeGhcM a -> IO a
runIGM = runIGM' id
runIGM' :: (Config.Config -> Config.Config) -> IdePlugins -> FilePath -> IdeGhcM a -> IO a
runIGM' modifyConfig testPlugins fp f = do
stateVar <- newTVarIO $ IdeState emptyModuleCache Map.empty Map.empty Nothing
crdl <- Bios.findLocalCradle fp
mlibdir <- Bios.getProjectGhcLibDir crdl
let tmpFuncs :: LspFuncs Config.Config
tmpFuncs = dummyLspFuncs
lspFuncs :: LspFuncs Config.Config
lspFuncs = tmpFuncs { config = (fmap . fmap) modifyConfig (config tmpFuncs)}
runIdeGhcM mlibdir testPlugins lspFuncs stateVar f
withFileLogging :: FilePath -> IO a -> IO a
withFileLogging logFile f = do
let logDir = "./test-logs"
logPath = logDir </> logFile
dirExists <- doesDirectoryExist logDir
unless dirExists $ createDirectory logDir
exists <- doesFileExist logPath
when exists $ removeFile logPath
setupLogger (Just logPath) ["hie"] L.DEBUG
f
-- ---------------------------------------------------------------------
-- If an executable @stack@ is present on the system then setup stack files,
-- otherwise specify a direct cradle with -isrc
setupBuildToolFiles :: IO ()
setupBuildToolFiles = do
stack <- findExecutable "stack"
let s = case stack of
Nothing -> setupDirectFilesIn
Just _ -> setupStackFilesIn
forM_ files $ \f -> do
s f
-- Cleanup stack directory in case the presence of stack has changed since
-- the last run
removePathForcibly (f ++ ".stack-work")
setupStackFilesIn :: FilePath -> IO ()
setupStackFilesIn f = do
resolver <- readResolver
writeFile (f ++ "stack.yaml") $ stackFileContents resolver
case f of
"./test/testdata/" -> writeFile (f ++ "hie.yaml") testdataHieYamlCradleStackContents
_ -> writeFile (f ++ "hie.yaml") hieYamlCradleStackContents
setupDirectFilesIn :: FilePath -> IO ()
setupDirectFilesIn f =
writeFile (f ++ "hie.yaml") hieYamlCradleDirectContents
-- ---------------------------------------------------------------------
files :: [FilePath]
files =
[ "./test/testdata/"
, "./test/testdata/addPackageTest/cabal-exe/"
, "./test/testdata/addPackageTest/hpack-exe/"
, "./test/testdata/addPackageTest/cabal-lib/"
, "./test/testdata/addPackageTest/hpack-lib/"
, "./test/testdata/addPragmas/"
, "./test/testdata/badProjects/cabal/"
, "./test/testdata/completion/"
, "./test/testdata/definition/"
, "./test/testdata/gototest/"
, "./test/testdata/redundantImportTest/"
, "./test/testdata/wErrorTest/"
]
data GhcVersion
= GHC88
| GHC86
| GHC84
deriving (Eq,Show)
ghcVersion :: GhcVersion
#if (defined(MIN_VERSION_GLASGOW_HASKELL) && (MIN_VERSION_GLASGOW_HASKELL(8,8,0,0)))
ghcVersion = GHC88
#elif (defined(MIN_VERSION_GLASGOW_HASKELL) && (MIN_VERSION_GLASGOW_HASKELL(8,6,0,0)))
ghcVersion = GHC86
#elif (defined(MIN_VERSION_GLASGOW_HASKELL) && (MIN_VERSION_GLASGOW_HASKELL(8,4,0,0)))
ghcVersion = GHC84
#endif
stackYaml :: FilePath
stackYaml =
#if (defined(MIN_VERSION_GLASGOW_HASKELL) && (MIN_VERSION_GLASGOW_HASKELL(8,8,3,0)))
"stack-8.8.3.yaml"
#elif (defined(MIN_VERSION_GLASGOW_HASKELL) && (MIN_VERSION_GLASGOW_HASKELL(8,8,2,0)))
"stack-8.8.2.yaml"
#elif (defined(MIN_VERSION_GLASGOW_HASKELL) && (MIN_VERSION_GLASGOW_HASKELL(8,8,1,0)))
"stack-8.8.1.yaml"
#elif (defined(MIN_VERSION_GLASGOW_HASKELL) && (MIN_VERSION_GLASGOW_HASKELL(8,6,5,0)))
"stack-8.6.5.yaml"
#elif (defined(MIN_VERSION_GLASGOW_HASKELL) && (MIN_VERSION_GLASGOW_HASKELL(8,6,4,0)))
"stack-8.6.4.yaml"
#elif (defined(MIN_VERSION_GLASGOW_HASKELL) && (MIN_VERSION_GLASGOW_HASKELL(8,6,3,0)))
"stack-8.6.3.yaml"
#elif (defined(MIN_VERSION_GLASGOW_HASKELL) && (MIN_VERSION_GLASGOW_HASKELL(8,6,2,0)))
"stack-8.6.2.yaml"
#elif (defined(MIN_VERSION_GLASGOW_HASKELL) && (MIN_VERSION_GLASGOW_HASKELL(8,6,1,0)))
"stack-8.6.1.yaml"
#elif (defined(MIN_VERSION_GLASGOW_HASKELL) && (MIN_VERSION_GLASGOW_HASKELL(8,4,4,0)))
"stack-8.4.4.yaml"
#elif (defined(MIN_VERSION_GLASGOW_HASKELL) && (MIN_VERSION_GLASGOW_HASKELL(8,4,3,0)))
"stack-8.4.3.yaml"
#elif (defined(MIN_VERSION_GLASGOW_HASKELL) && (MIN_VERSION_GLASGOW_HASKELL(8,4,2,0)))
"stack-8.4.2.yaml"
#endif
logFilePath :: String
logFilePath = "hie-" ++ stackYaml ++ ".log"
-- | The command to execute the version of hie for the current compiler.
--
-- Both @stack test@ and @cabal new-test@ setup the environment so @hie@ is
-- on PATH. Cabal seems to respond to @build-tool-depends@ specifically while
-- stack just puts all project executables on PATH.
hieCommand :: String
hieCommand = "hie --lsp --bios-verbose -d -l test-logs/" ++ logFilePath
hieCommandVomit :: String
hieCommandVomit = hieCommand ++ " --vomit"
hieCommandExamplePlugin :: String
hieCommandExamplePlugin = hieCommand ++ " --example"
-- |Choose a resolver based on the current compiler, otherwise HaRe/ghc-mod will
-- not be able to load the files
readResolver :: IO String
readResolver = readResolverFrom stackYaml
newtype StackResolver = StackResolver String
instance FromJSON StackResolver where
parseJSON (Object x) = StackResolver <$> x .: pack "resolver"
parseJSON invalid = typeMismatch "StackResolver" invalid
readResolverFrom :: FilePath -> IO String
readResolverFrom yamlPath = do
result <- decodeFileEither yamlPath
case result of
Left err -> error $ yamlPath ++ " parsing failed: " ++ show err
Right (StackResolver res) -> return res
-- ---------------------------------------------------------------------
hieYamlCradleStackContents :: String
hieYamlCradleStackContents = unlines
[ "# WARNING: THIS FILE IS AUTOGENERATED IN test/utils/TestUtils.hs. IT WILL BE OVERWRITTEN ON EVERY TEST RUN"
, "cradle:"
, " stack:"
]
testdataHieYamlCradleStackContents :: String
testdataHieYamlCradleStackContents = unlines
[ "# WARNING: THIS FILE IS AUTOGENERATED IN test/utils/TestUtils.hs. IT WILL BE OVERWRITTEN ON EVERY TEST RUN"
, "cradle:"
, " stack:"
, " - path: \"ApplyRefact.hs\""
, " component: \"testdata:exe:applyrefact\""
, " - path: \"ApplyRefact2.hs\""
, " component: \"testdata:exe:applyrefact2\""
, " - path: \"CodeActionRename.hs\""
, " component: \"testdata:exe:codeactionrename\""
, " - path: \"Hover.hs\""
, " component: \"testdata:exe:hover\""
, " - path: \"Symbols.hs\""
, " component: \"testdata:exe:symbols\""
, " - path: \"ApplyRefact2.hs\""
, " component: \"testdata:exe:applyrefact2\""
, " - path: \"HlintPragma.hs\""
, " component: \"testdata:exe:hlintpragma\""
, " - path: \"HaReCase.hs\""
, " component: \"testdata:exe:harecase\""
, " - path: \"HaReDemote.hs\""
, " component: \"testdata:exe:haredemote\""
, " - path: \"HaReMoveDef.hs\""
, " component: \"testdata:exe:haremovedef\""
, " - path: \"HaReRename.hs\""
, " component: \"testdata:exe:harerename\""
, " - path: \"HaReGA1.hs\""
, " component: \"testdata:exe:haregenapplicative\""
, " - path: \"FuncTest.hs\""
, " component: \"testdata:exe:functests\""
, " - path: \"liquid/Evens.hs\""
, " component: \"testdata:exe:evens\""
, " - path: \"FileWithWarning.hs\""
, " component: \"testdata:exe:filewithwarning\""
, " - path: ."
, " component: \"testdata:exe:filewithwarning\""
]
hieYamlCradleDirectContents :: String
hieYamlCradleDirectContents = unlines
[ "# WARNING: THIS FILE IS AUTOGENERATED IN test/utils/TestUtils.hs. IT WILL BE OVERWRITTEN ON EVERY TEST RUN"
, "cradle:"
, " direct:"
, " arguments:"
, " - -isrc"
]
stackFileContents :: String -> String
stackFileContents resolver = unlines
[ "# WARNING: THIS FILE IS AUTOGENERATED IN test/utils/TestUtils. IT WILL BE OVERWRITTEN ON EVERY TEST RUN"
, "resolver: " ++ resolver
, "packages:"
, "- '.'"
, "extra-deps: []"
, "flags: {}"
, "extra-package-dbs: []"
]
-- ---------------------------------------------------------------------
getHspecFormattedConfig :: String -> IO Config
getHspecFormattedConfig name = do
-- https://circleci.com/docs/2.0/env-vars/#built-in-environment-variables
isCI <- isJust <$> lookupEnv "CI"
-- Only use the xml formatter on CI since it hides console output
if isCI
then do
let subdir = "test-results" </> name
createDirectoryIfMissing True subdir
return $ defaultConfig { configFormatter = Just xmlFormatter
, configOutputFile = Right $ subdir </> "results.xml"
}
else return defaultConfig
-- | A Hspec formatter for CircleCI.
-- Originally from https://github.com/LeastAuthority/hspec-jenkins
xmlFormatter :: Formatter
xmlFormatter = silent {
headerFormatter = do
writeLine "<?xml version='1.0' encoding='UTF-8'?>"
writeLine "<testsuite>"
, exampleSucceeded
, exampleFailed
, examplePending
, footerFormatter = writeLine "</testsuite>"
}
where
#if MIN_VERSION_hspec(2,5,0)
exampleSucceeded path _ =
#else
exampleSucceeded path =
#endif
writeLine $ renderMarkup $ testcase path ""
#if MIN_VERSION_hspec(2,5,0)
exampleFailed path _ err =
#else
exampleFailed path (Left err) =
writeLine $ renderMarkup $ testcase path $
failure ! message (show err) $ ""
exampleFailed path (Right err) =
#endif
writeLine $ renderMarkup $ testcase path $
failure ! message (reasonAsString err) $ ""
#if MIN_VERSION_hspec(2,5,0)
examplePending path _ reason =
#else
examplePending path reason =
#endif
writeLine $ renderMarkup $ testcase path $
case reason of
Just desc -> skipped ! message desc $ ""
Nothing -> skipped ""
failure, skipped :: Markup -> Markup
failure = customParent "failure"
skipped = customParent "skipped"
name, className, message :: String -> Attribute
name = customAttribute "name" . stringValue
className = customAttribute "classname" . stringValue
message = customAttribute "message" . stringValue
testcase :: Path -> Markup -> Markup
testcase (xs,x) = customParent "testcase" ! name x ! className (intercalate "." xs)
reasonAsString :: FailureReason -> String
reasonAsString NoReason = "no reason given"
reasonAsString (Reason x) = x
reasonAsString (ExpectedButGot Nothing expected got) = "Expected " ++ expected ++ " but got " ++ got
reasonAsString (ExpectedButGot (Just src) expected got) = src ++ " expected " ++ expected ++ " but got " ++ got
#if MIN_VERSION_hspec(2,5,0)
reasonAsString (Error Nothing err ) = show err
reasonAsString (Error (Just s) err) = s ++ show err
#endif
-- ---------------------------------------------------------------------
flushStackEnvironment :: IO ()
flushStackEnvironment = do
-- We need to clear these environment variables to prevent
-- collisions with stack usages
-- See https://github.com/commercialhaskell/stack/issues/4875
unsetEnv "GHC_PACKAGE_PATH"
unsetEnv "GHC_ENVIRONMENT"
unsetEnv "HASKELL_PACKAGE_SANDBOX"
unsetEnv "HASKELL_PACKAGE_SANDBOXES"
-- ---------------------------------------------------------------------
dummyLspFuncs :: Default a => LspFuncs a
dummyLspFuncs = LspFuncs { clientCapabilities = def
, config = return (Just def)
, sendFunc = const (return ())
, getVirtualFileFunc = const (return Nothing)
, persistVirtualFileFunc = \uri -> return (uriToFilePath (fromNormalizedUri uri))
, reverseFileMapFunc = return id
, publishDiagnosticsFunc = mempty
, flushDiagnosticsBySourceFunc = mempty
, getNextReqId = pure (IdInt 0)
, rootPath = Nothing
, getWorkspaceFolders = return Nothing
, withProgress = \_ _ f -> f (const (return ()))
, withIndefiniteProgress = \_ _ f -> f
}