-
Notifications
You must be signed in to change notification settings - Fork 9
/
shelltestrunner.hs
294 lines (248 loc) · 9.57 KB
/
shelltestrunner.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
#!/usr/bin/env runhaskell
{-
shelltestrunner - a handy tool for testing command-line programs.
See shelltestrunner.cabal.
(c) Simon Michael 2009, released under GNU GPLv3
-}
module Main
where
import Control.Concurrent (forkIO)
import Control.Concurrent.MVar (newEmptyMVar, putMVar, takeMVar)
import Control.Monad (liftM,when)
import Data.List (partition, intercalate)
import Data.Maybe (fromJust,isJust,maybe,isNothing,catMaybes)
import qualified Test.HUnit (Test)
import System.Console.ParseArgs hiding (args)
import System.Environment (withArgs)
import System.Exit (ExitCode(..),exitWith)
import System.IO (Handle, hGetContents, hPutStr)
import System.Process (runInteractiveCommand, waitForProcess)
import Test.Framework (defaultMain)
import Test.Framework.Providers.HUnit (hUnitTestToTests)
import Test.HUnit hiding (Test)
import Text.ParserCombinators.Parsec
import Text.Printf (printf)
import Text.RegexPR
import Debug.Trace
strace :: Show a => a -> a
strace a = trace (show a) a
version :: String
version = "0.6" -- keep synced with .cabal
data ArgId = HelpFlag
| VersionFlag
| DebugFlag
| ImplicitTestsFlag
| ExecutableArg
deriving (Ord, Eq, Show)
argspec :: [Arg ArgId]
argspec = [
Arg {argIndex = HelpFlag,
argName = Just "help",
argAbbr = Just 'h',
argData = Nothing,
argDesc = "show help"
}
,Arg {argIndex = VersionFlag,
argName = Just "version",
argAbbr = Just 'V',
argData = Nothing,
argDesc = "show version"
}
,Arg {argIndex = DebugFlag,
argName = Just "debug",
argAbbr = Just 'd',
argData = Nothing,
argDesc = "show verbose debugging output"
}
,Arg {argIndex = ImplicitTestsFlag,
argName = Just "implicit-tests",
argAbbr = Just 'i',
argData = Nothing,
argDesc = "provide implicit tests for all omitted fields"
}
,Arg {argIndex = ExecutableArg,
argName = Nothing,
argAbbr = Nothing,
argData = argDataRequired "executable" ArgtypeString,
argDesc = "executable program or shell command to test"
}
]
data ShellTest = ShellTest {
testname :: String
,commandargs :: String
,stdin :: Maybe String
,stdoutExpected :: Maybe Matcher
,stderrExpected :: Maybe Matcher
,exitCodeExpected :: Maybe Matcher
} deriving (Show)
type Regex = String
data Matcher = Lines String
| Numeric String
| PositiveRegex Regex
| NegativeRegex Regex
deriving (Show)
main :: IO ()
main = do
args <- parseArgsIO ArgsTrailing argspec
-- parseargs issue: exits at first gotArg if there's no exe argument
when (args `gotArg` VersionFlag) printVersion
when (args `gotArg` HelpFlag) $ printHelp args
let (unprocessedopts, testfiles) = partition ((=="-").take 1) $ argsRest args
when (args `gotArg` DebugFlag) $ do
putStrLn $ "testing executable: " ++ (show $ fromJust $ getArgString args ExecutableArg)
putStrLn $ "unprocessed options: " ++ show unprocessedopts
putStrLn $ "test files: " ++ show testfiles
shelltests <- liftM concat $ mapM (parseShellTestFile args) testfiles
withArgs unprocessedopts $ defaultMain $ concatMap (hUnitTestToTests.shellTestToHUnitTest args) shelltests
printVersion :: IO ()
printVersion = putStrLn version >> exitWith ExitSuccess
printHelp :: Args ArgId -> IO ()
printHelp args = putStrLn (argsUsage args) >> exitWith ExitSuccess
-- parsing
parseShellTestFile :: Args ArgId -> FilePath -> IO [ShellTest]
parseShellTestFile args f = do
when (args `gotArg` DebugFlag) $ putStrLn $ "parsing file: " ++ f
ts <- liftM (either (error.show) id) $ parseFromFile (many shelltestp) f
let ts' | length ts > 1 = [t{testname=testname t++":"++show n} | (n,t) <- zip ([1..]::[Int]) ts]
| otherwise = ts
when (args `gotArg` DebugFlag) $ putStrLn $ "parsed tests: " ++ show ts'
return ts'
shelltestp :: Parser ShellTest
shelltestp = do
st <- getParserState
let f = sourceName $ statePos st
many commentlinep
c <- commandargsp
i <- optionMaybe inputp
o <- optionMaybe expectedoutputp
e <- optionMaybe expectederrorp
x <- optionMaybe expectedexitcodep
when (null c && (isNothing i) && (null $ catMaybes [o,e,x])) $ fail "empty test file"
return ShellTest{testname=f,commandargs=c,stdin=i,stdoutExpected=o,stderrExpected=e,exitCodeExpected=x}
linep,commentlinep,commandargsp,delimiterp,inputp,whitespacep :: Parser String
linep = anyChar `manyTill` newline
commentlinep = char '#' >> anyChar `manyTill` newline
commandargsp = linep
delimiterp = choice [try $ string "<<<", try $ string ">>>", (eof >> return "")]
inputp = string "<<<" >> newline >> (liftM unlines) (linep `manyTill` (lookAhead delimiterp))
expectedoutputp :: Parser Matcher
expectedoutputp = try $ do
string ">>>" >> optional (char '1')
whitespacep
choice [positiveregexmatcherp, negativeregexmatcherp, linesmatcherp]
expectederrorp :: Parser Matcher
expectederrorp = try $ do
string ">>>2"
whitespacep
choice [positiveregexmatcherp, negativeregexmatcherp, linesmatcherp]
expectedexitcodep :: Parser Matcher
expectedexitcodep = do
string ">>>="
whitespacep
choice [positiveregexmatcherp, negativeregexmatcherp, numericmatcherp]
negativeregexmatcherp :: Parser Matcher
negativeregexmatcherp = do
char '!'
PositiveRegex r <- positiveregexmatcherp
return $ NegativeRegex r
positiveregexmatcherp :: Parser Matcher
positiveregexmatcherp = do
char '/'
r <- many $ noneOf "/"
char '/'
whitespacep
newline
return $ PositiveRegex r
linesmatcherp :: Parser Matcher
linesmatcherp = do
whitespacep
newline
(liftM $ Lines . unlines) (linep `manyTill` (lookAhead delimiterp))
numericmatcherp :: Parser Matcher
numericmatcherp = do
s <- many1 $ oneOf "0123456789"
whitespacep
newline
return $ Numeric s
whitespacep = many $ oneOf " \t"
-- running
shellTestToHUnitTest :: Args ArgId -> ShellTest -> Test.HUnit.Test
shellTestToHUnitTest args ShellTest{testname=n,commandargs=c,stdin=i,stdoutExpected=o_expected,
stderrExpected=e_expected,exitCodeExpected=x_expected} =
n ~: do
let exe = fromJust $ getArgString args ExecutableArg
cmd = unwords [exe,c]
(o_expected',e_expected',x_expected') =
case (args `gotArg` ImplicitTestsFlag) of
True -> (case o_expected of
Just m -> Just m
_ -> Just $ Lines ""
,case e_expected of Just m -> Just m
_ -> Just $ Lines ""
,case x_expected of Just m -> Just m
_ -> Just $ Numeric "0")
False -> (o_expected,e_expected,x_expected)
when (args `gotArg` DebugFlag) $ do
putStrLn $ "running test: " ++ n
putStrLn $ "running command: " ++ cmd
-- run the command, passing it the stdin if any, and reading the
-- stdout/stderr/exit code. This has to be done carefully.
(ih,oh,eh,ph) <- runInteractiveCommand cmd
when (isJust i) $ forkIO (hPutStr ih $ fromJust i) >> return ()
o <- newEmptyMVar
e <- newEmptyMVar
forkIO $ oh `hGetContentsStrictlyAnd` putMVar o
forkIO $ eh `hGetContentsStrictlyAnd` putMVar e
x_actual <- waitForProcess ph >>= return.fromExitCode
o_actual <- takeMVar o
e_actual <- takeMVar e
let failuremsg
-- when a bad exe is provided, we don't want to show all the test
-- failures. This should work on all posix systems at least.
-- Really we should report a test error here, not a failure.
| x_actual == 127 = cmd ++ ": command not found"
| otherwise = addnewline $ intercalate "\n" $ filter (not . null) [
if (maybe True (o_actual `matches`) o_expected')
then ""
else showExpectedActual "stdout" (fromJust o_expected') o_actual
,if (maybe True (e_actual `matches`) e_expected')
then ""
else showExpectedActual "stderr" (fromJust e_expected') e_actual
,if (maybe True (show x_actual `matches`) x_expected')
then ""
else showExpectedActual "exit code" (fromJust x_expected') (show x_actual)
]
assertString failuremsg
where addnewline "" = ""
addnewline s = "\n"++s
hGetContentsStrictlyAnd :: Handle -> (String -> IO b) -> IO b
hGetContentsStrictlyAnd h f = hGetContents h >>= \c -> length c `seq` f c
matches :: String -> Matcher -> Bool
matches s (PositiveRegex r) = s `containsRegex` r
matches s (NegativeRegex r) = not $ s `containsRegex` r
matches s (Numeric p) = s == p
matches s (Lines p) = s == p
showExpectedActual :: String -> Matcher -> String -> String
showExpectedActual field e a =
printf "**Expected %s:%s**Got %s:\n%s" field (showMatcher e) field a
showMatcher :: Matcher -> String
showMatcher (PositiveRegex r) = " /"++r++"/\n"
showMatcher (NegativeRegex r) = " !/"++r++"/\n"
showMatcher (Numeric s) = "\n"++s++"\n"
showMatcher (Lines s) = "\n"++s
-- utils
-- toExitCode :: Int -> ExitCode
-- toExitCode 0 = ExitSuccess
-- toExitCode n = ExitFailure n
fromExitCode :: ExitCode -> Int
fromExitCode ExitSuccess = 0
fromExitCode (ExitFailure n) = n
strip,lstrip,rstrip,dropws :: String -> String
strip = lstrip . rstrip
lstrip = dropws
rstrip = reverse . dropws . reverse
dropws = dropWhile (`elem` " \t")
containsRegex :: String -> String -> Bool
containsRegex s r = case matchRegexPR (""++r) s of
Just _ -> True
_ -> False