Debian Codegraph @

src/Test/Golden.agda

raw
1 ------------------------------------------------------------------------
2 -- The Agda standard library
3 --
4 -- Golden testing framework
5 ------------------------------------------------------------------------
6
7 -- This is a port of the golden testing framework used by the Idris2
8 -- compiler and various Idris2 libraries.
9 -- It provides the core features required to perform golden file testing.
10 --
11 -- We provide the core functionality to run a *single* golden file test,
12 -- or a whole test tree. This allows the developer freedom to use as is
13 -- or design the rest of the test harness to their liking.
14
15 ------------------------------------------------------------------------
16 -- Test Structure
17 --
18 -- This harness works from the assumption that each individual golden
19 -- test comprises of a directory with the following structure:
20 --
21 -- + `run` a *shell* script that runs the test. We expect it to:
22 -- * Use `$1` as the variable standing for the Agda executable to be tested
23 -- * Clean up after itself (e.g. by running `rm -rf build/`)
24 --
25 -- + `expected` a file containing the expected output of `run`
26 --
27 -- During testing, the test harness will generate an `output` file.
28 -- It will be compared to the `expected` golden file provided by the user.
29 -- In case there is a mismatch, the framework will:
30
31 -- + either display output & expected if the session is not interactive
32 -- + or use the following command line to produce a diff and ask the user
33 -- whether they want to overwrite the currently `expected` value:
34 --
35 -- git diff --no-index --exit-code --word-diff=color expected output
36 --
37 -- If `git` fails then the runner will simply present the expected and
38 -- 'given' files side-by-side.
39 --
40 -- Of note, it is helpful to add `output` to a local `.gitignore` instance
41 -- to ensure that it is not mistakenly versioned.
42
43
44 ------------------------------------------------------------------------
45 -- Options
46 --
47 -- The test harness has several options that may be set:
48 --
49 -- + `exeUnderTest` The path of the executable we are testing (typically `agda`)
50 -- + `onlyNames` The tests to run relative to the generated executable.
51 -- + `onlyFile` The file listing the tests to run relative to the generated executable.
52 -- + `interactive` Whether to offer to update the expected file or not.
53 -- + `timing` Whether to display time taken for each test.
54 -- + `failureFile` The file in which to write the list of failing tests.
55 -- + `colour` The output should use ANSI escape codes
56 --
57 -- We provide an options parser (`options`) that takes the list of command line
58 -- arguments and constructs this for you.
59 --
60
61 ------------------------------------------------------------------------
62 -- Usage
63 --
64 -- When compiled to an executable the expected usage is:
65 --
66 --```sh
67 --runtests <path to executable under test>
68 -- [--timing]
69 -- [--interactive]
70 -- [--only-file PATH]
71 -- [--failure-file PATH]
72 -- [--no-colour]
73 -- [--only [NAMES]]
74 --```
75 --
76 -- assuming that the test runner is compiled to an executable named `runtests`.
77
78 {-# OPTIONS --cubical-compatible --guardedness #-}
79
80 module Test.Golden where
81
82 open import Data.Bool.Base using (Bool; true; false; if_then_else_)
83 import Data.Char as Char
84 open import Data.Fin using (#_)
85 import Data.Integer.Base as ℤ
86 open import Data.List.Base as List using (List; []; _∷_; _++_; filter; partitionSums)
87 open import Data.List.Relation.Binary.Infix.Heterogeneous.Properties using (infix?)
88 open import Data.List.Relation.Unary.Any using (any?)
89 open import Data.Maybe.Base using (Maybe; just; nothing; fromMaybe)
90 open import Data.Nat.Base using (ℕ; _≡ᵇ_; _<ᵇ_; _+_; _∸_)
91 open import Data.Nat.ListAction using (sum)
92 import Data.Nat.Show as ℕ using (show)
93 open import Data.Product.Base using (_×_; _,_)
94 open import Data.String.Base as String using (String; lines; unlines; unwords; concat)
95 open import Data.String.Properties as String using (_≟_)
96 open import Data.Sum.Base using (_⊎_; inj₁; inj₂)
97 open import Data.Unit.Base using (⊤)
98
99 open import Function.Base using (id; _$_; case_of_)
100
101 open import Relation.Nullary.Decidable.Core using (does)
102
103 open import Codata.Musical.Notation using (♯_)
104 open import IO
105
106 open import System.Clock as Clock using (time′; Time; seconds)
107 open import System.Console.ANSI
108 open import System.Directory using (doesFileExist; doesDirectoryExist)
109 open import System.Environment using (getArgs; lookupEnv)
110 open import System.Exit
111 open import System.FilePath.Posix using (mkFilePath)
112 open import System.Process using (callCommand; system)
113
114 record Options : Set where
115 field
116 -- What is the name of the Agda executable?
117 exeUnderTest : String
118 -- Should we only run some specific cases?
119 onlyNames : List String
120 -- Should we run the test suite interactively?
121 interactive : Bool
122 -- Should we time and display the tests?
123 timing : Bool
124 -- Should we write the list of failing cases to a file?
125 failureFile : Maybe String
126 -- Should we use ANSI escape codes to colour the output?
127 colour : Bool
128 open Options
129
130 initOptions : String → Options
131 initOptions exe = record
132 { exeUnderTest = exe
133 ; onlyNames = []
134 ; interactive = false
135 ; timing = false
136 ; failureFile = nothing
137 ; colour = true
138 }
139
140 usage : String
141 usage = unwords
142 $ "Usage:"
143 ∷ "runtests <path>"
144 ∷ "[--timing]"
145 ∷ "[--interactive]"
146 ∷ "[--failure-file PATH]"
147 ∷ "[--only-file PATH]"
148 ∷ "[--no-colour]"
149 ∷ "[--only [NAMES]]"
150 ∷ []
151
152 data Error : Set where
153 MissingExecutable : Error
154 InvalidArgument : String → Error
155
156 show : Error → String
157 show MissingExecutable = "Expected a path to Agda, got nothing"
158 show (InvalidArgument arg) = "Invalid argument: " String.++ arg
159
160 -- Process the command line options
161 options : List String → IO (Error ⊎ Options)
162 options(exe ∷ rest) = mkOptions exe rest where
163
164 go : List String → Maybe String → Options → String ⊎ (Maybe String × Options)
165 go [] mfp opts = inj₂ (mfp , opts)
166 go ("--timing" ∷ args) mfp opts =
167 go args mfp (record opts { timing = true })
168 go ("--interactive" ∷ args) mfp opts =
169 go args mfp (record opts { interactive = true })
170 go ("--failure-file" ∷ fp ∷ args) mfp opts =
171 go args mfp (record opts { failureFile = just fp })
172 go ("--only" ∷ args) mfp opts =
173 inj₂ (mfp , (record opts { onlyNames = args }))
174 go ("--only-file" ∷ fp ∷ args) mfp opts =
175 go args (just fp) (record opts { onlyNames = args })
176 go ("--no-colour" ∷ args) mfp opts =
177 go args mfp (record opts { colour = false })
178 go (arg ∷ _) _ _ = inj₁ arg
179
180 mkOptions : String → List String → IO (Error ⊎ Options)
181 mkOptions exe rest = do
182 inj₂ (mfp , opts) ← pure $ go rest nothing (initOptions exe)
183 where inj₁ arg → pure (inj₁ (InvalidArgument arg))
184 term ← fromMaybe "" <$> lookupEnv "TERM"
185 let opts = if does (term ≟ "DUMB")
186 then record opts { colour = false }
187 else opts
188 just fp ← pure mfp
189 where _ → pure (inj₂ opts)
190 only ← readFiniteFile fp
191 pure $ inj₂ $ record opts { onlyNames = lines only ++ onlyNames opts }
192
193 options [] = pure (inj₁ MissingExecutable)
194
195
196 -- The result of a test run
197 -- `Left` corresponds to a failure and `Right` to a success
198 Result : Set
199 Result = String ⊎ String
200
201 -- Run the specified golden test with the supplied options.
202 runTest : Options → String → IO Result
203 runTest opts testPath = do
204
205 true ← doesDirectoryExist (mkFilePath testPath)
206 where false → fail directoryNotFound
207
208 time ← time′ $ callCommand $ unwords
209 $ "cd" ∷ testPath
210 ∷ "&&" ∷ "sh ./run" ∷ opts .exeUnderTest
211 ∷ "| tr -d '\\r' > output"
212 ∷ []
213
214 just out ← readLocalFile "output"
215 where nothing → fail (fileNotFound "output")
216 just exp ← readLocalFile "expected"
217 where nothing → do if opts .interactive
218 then mayOverwrite nothing out
219 else putStrLn (fileNotFound "expected")
220 pure (inj₁ testPath)
221
222 let result = does (out String.≟ exp)
223
224 if result
225 then printTiming (opts .timing) time
226 $ if opts .colour
227 then withCommand (setColour foreground classic green)
228 else id
229 $ "success"
230 else do printTiming (opts .timing) time
231 $ if opts .colour
232 then withCommand (setColour foreground bright red)
233 else id
234 $ "FAILURE"
235 if opts .interactive
236 then mayOverwrite (just exp) out
237 else putStrLn (unlines (expVsOut exp out))
238
239 pure $ if result then inj₂ testPath else inj₁ testPath
240
241 where
242
243 directoryNotFound : String
244 directoryNotFound = unwords
245 $ "Directory"
246 ∷ testPath
247 ∷ "does not exist" ∷ []
248
249 fileNotFound : String → String
250 fileNotFound name = unwords
251 $ "File"
252 ∷ (testPath String.++ "/output")
253 ∷ "does not exist" ∷ []
254
255 fail : String → IO Result
256 fail msg = do putStrLn msg
257 pure (inj₁ testPath)
258
259 readLocalFile : String → IO (Maybe String)
260 readLocalFile name = do
261 let fp = concat (testPath ∷ "/" ∷ name ∷ [])
262 true ← doesFileExist (mkFilePath fp)
263 where false → pure nothing
264 just <$> readFiniteFile fp
265
266 getAnswer : IO Bool
267 getAnswer = untilJust $ do
268 str ← getLine
269 case str of λ where
270 "y" → pure $ just true
271 "n" → pure $ just false
272 "" → pure $ just false -- default answer is no
273 _ → do putStrLn "Invalid answer."
274 pure nothing
275
276 expVsOut : String → String → List String
277 expVsOut exp out = "Expected:" ∷ exp ∷ "Given:" ∷ out ∷ []
278
279 hasFailed : ExitCode → Bool
280 hasFailed ExitSuccess = false
281 hasFailed (ExitFailure code) = code ℤ.≤ᵇ ℤ.+ 0
282
283 mayOverwrite : Maybe String → String → IO _
284 mayOverwrite mexp out = do
285 case mexp of λ where
286 nothing → putStrLn $ unlines
287 $ "Golden value missing. I computed the following result:"
288 ∷ out
289 ∷ "Accept new golden value? [y/N]"
290 ∷ []
291 (just exp) → do
292 code ← system $ concat
293 $ "git diff --no-index --exit-code --word-diff=color "
294 ∷ testPath ∷ "/expected "
295 ∷ testPath ∷ "/output"
296 ∷ []
297 putStrLn $ unlines
298 $ "Golden value differs from actual value."
299 ∷ (if hasFailed code then expVsOut exp out else [])
300 ++ "Accept actual value as new golden value? [y/N]"
301 ∷ []
302
303 b ← getAnswer
304 when b $ writeFile (testPath String.++ "/expected") out
305
306 printTiming : Bool → Time → String → IO _
307 printTiming false _ msg = putStrLn $ concat (testPath ∷ ": " ∷ msg ∷ [])
308 printTiming true time msg =
309 let time = ℕ.show (time .seconds) String.++ "s"
310 spent = 9 + sum (List.map String.length (testPath ∷ time ∷ []))
311 -- ^ hack: both "success" and "FAILURE" have the same length
312 -- can't use `String.length msg` because the msg contains escape codes
313 pad = String.replicate (72 ∸ spent) ' '
314 in putStrLn (concat (testPath ∷ ": " ∷ msg ∷ pad ∷ time ∷ []))
315
316 -- A test pool is characterised by
317 -- + a name
318 -- + and a list of directory paths
319 record TestPool : Set where
320 constructor mkTestPool
321 field
322 poolName : String
323 testCases : List String
324 open TestPool
325
326 module Summary where
327
328 -- The summary of a test pool run
329 record Summary : Set where
330 constructor mkSummary
331 field
332 success : List String
333 failure : List String
334 open Summary public
335
336 init : Summary
337 init = mkSummary [] []
338
339 merge : Summary → Summary → Summary
340 merge (mkSummary ws1 ls1) (mkSummary ws2 ls2) =
341 mkSummary (ws2 ++ ws1) (ls2 ++ ls1)
342
343 update : List Result → Summary → Summary
344 update res sum =
345 let (ls2 , ws2) = partitionSums res in
346 merge sum (mkSummary ws2 ls2)
347
348 open Summary using (Summary) hiding (module Summary)
349
350 -- Only keep the tests that have been asked for
351 filterTests : Options → List String → List String
352 filterTests opts = case onlyNames opts of λ where
353 [] → id
354 xs → let names = List.map String.toList xs in
355 filter (λ n → any? (λ m → infix? Char._≟_ m (String.toList n)) names)
356
357 poolRunner : Options → TestPool → IO Summary
358 poolRunner opts pool = do
359 -- check there is a non-empty list of tests we want to run
360 let tests = filterTests opts (pool .testCases)
361 (_ ∷ _) ← pure tests
362 where [] → pure Summary.init
363
364 -- announce the test pool and run them
365 putStrLn banner
366 loop Summary.init tests
367
368 where
369
370 separator : String
371 separator = String.replicate 72 '-'
372
373 banner : String
374 banner = unlines
375 $ "" ∷ separator
376 ∷ pool .poolName
377 ∷ separator ∷ ""
378 ∷ []
379
380 loop : Summary → List String → IO Summary
381 loop acc [] = pure acc
382 loop acc (test ∷ tests) = do
383 res <- runTest opts test
384 loop (Summary.update (res ∷ []) acc) tests
385
386 runner : List TestPool → IO ⊤
387 runner tests = do
388 -- figure out the options
389 args ← getArgs
390 inj₂ opts ← options args
391 where inj₁ err → die (unlines (show err ∷ usage ∷ []))
392
393 -- run the tests
394 ress ← List.mapM (poolRunner opts) tests
395 let open Summary
396 let res = List.foldl merge init ress
397
398 -- report the result
399 let nsucc = List.length (res .success)
400 let nfail = List.length (res .failure)
401 let ntotal = nsucc + nfail
402 putStrLn $ concat $ ℕ.show nsucc ∷ "/" ∷ ℕ.show ntotal ∷ " tests successful" ∷ []
403
404 -- deal with failures
405 let list = unlines (res .failure)
406 when (0 <ᵇ nfail) $ do
407 putStrLn "Failing tests:"
408 putStrLn list
409 whenJust (opts .failureFile) $ λ fp → writeFile fp list
410
411 -- exit
412 if 0 ≡ᵇ nfail
413 then exitSuccess
414 else exitFailure