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
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE OverloadedStrings #-}
module Main (main) where
import Citeproc
import Citeproc.CslJson
import Data.Algorithm.DiffContext
import System.TimeIt (timeIt)
import Control.Monad (unless)
import Control.Monad.Trans.State
import Control.Monad.IO.Class (liftIO)
import System.Environment (getArgs)
import System.Exit
import System.Directory (getDirectoryContents, doesFileExist)
import Data.Text (Text)
import qualified Data.Set as Set
import qualified Text.PrettyPrint as Pretty
import qualified Data.Text as T
import qualified Data.Text.IO as TIO
import Data.List (foldl', isInfixOf, intersperse, sortOn, sort)
import Data.Containers.ListUtils (nubOrdOn)
import Data.Char (isDigit, isLetter, toLower)
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy as L
import qualified Data.Aeson as A
import Data.Aeson ((.:?), (.!=))
import Data.Text.Encoding (decodeUtf8)
import System.FilePath
import Data.Maybe (fromMaybe, isJust)
import Text.Printf (printf)
#if !MIN_VERSION_base(4,11,0)
import Data.Semigroup
#endif
data CiteprocTest a =
CiteprocTest
{ name :: Text
, path :: FilePath
, category :: Text
, mode :: Text
, result :: Text
, csl :: ByteString
, input :: [Reference a]
, bibentries :: Maybe A.Value
, bibsection :: Maybe A.Value
, citeItems :: Maybe [Citation a]
, citations :: Maybe [Citation a]
, abbreviations :: Maybe Abbreviations
, skipReason :: Maybe Text
, options :: Maybe TestOptions
} deriving (Show)
newtype TestOptions =
TestOptions { testCiteprocOpts :: CiteprocOptions }
deriving (Show, Eq)
defaultTestOptions :: TestOptions
defaultTestOptions = TestOptions
{ testCiteprocOpts = defaultCiteprocOptions }
instance A.FromJSON TestOptions where
parseJSON = A.withObject "TestOptions" $ fmap TestOptions . \v ->
CiteprocOptions
<$> v .:? "linkCitations" .!= False
<*> v .:? "linkBibliography" .!= False
data TestResult =
Passed
| Skipped Text
| Failed Text Text
| Errored CiteprocError
deriving (Show, Eq)
runTest :: CiteprocTest (CslJson Text)
-> StateT Counts IO TestResult
runTest test = do
let opts = fromMaybe defaultTestOptions . options $ test
let cites =
case citations test of
Just cs -> cs
Nothing ->
case citeItems test of
Nothing
| mode test == "citation"
-> [referencesToCitation
(nubOrdOn referenceId (input test))]
| otherwise
-> map (referencesToCitation . (:[]))
(nubOrdOn referenceId (input test))
Just cs -> cs
let doError err = do
modify $ \st -> st{ errored = category test : errored st }
liftIO $ do
TIO.putStrLn $ "[ERRORED] " <> T.pack (path test)
TIO.putStrLn $ T.pack $ show err
TIO.putStrLn ""
return $ Errored err
let doSkip reason = do
modify $ \st -> st{ skipped = category test : skipped st }
liftIO $ do
TIO.putStrLn $ "[SKIPPED] " <> T.pack (path test)
-- TIO.putStrLn $ T.strip reason
TIO.putStrLn ""
return $ Skipped reason
case skipReason test of
Just reason -> doSkip reason
Nothing ->
case parseStyle (const Nothing) (decodeUtf8 $ csl test) of
Nothing -> doError $ CiteprocParseError
"Could not fetch independent parent"
Just (Left err) -> doError err
Just (Right style') -> do
let style = style'{ styleAbbreviations = abbreviations test }
let loc = mergeLocales Nothing style
let actual = citeproc (testCiteprocOpts opts)
style Nothing (input test) cites
unless (null (resultWarnings actual)) $ do
liftIO $ do
TIO.putStrLn $ "[WARNING] " <> T.pack (path test)
mapM_ (TIO.putStrLn . ("==> " <>))
$ resultWarnings actual
case mode test of
"citation" -> compareTest test
(T.intercalate "\n" $ map (renderCslJson' loc)
(resultCitations actual))
"bibliography" -> compareTest test
(T.intercalate "\n"
(addDivs $ map (renderCslJson' loc . snd)
(resultBibliography actual)))
_ -> doSkip $ "unknown mode " <> mode test
renderCslJson' :: Locale -> CslJson Text -> Text
renderCslJson' loc x =
if T.null res
then "[CSL STYLE ERROR: reference with no printed form.]"
else res
where
res = renderCslJson True loc x
addDivs :: [Text] -> [Text]
addDivs ts = "<div class=\"csl-bib-body\">" : map addItemDiv ts ++ ["</div>"]
where addItemDiv t
| "<div" `T.isPrefixOf` t =
" <div class=\"csl-entry\">\n " <> t <> "\n </div>"
| "</div>" `T.isSuffixOf` t =
" <div class=\"csl-entry\">" <> t <> "\n </div>"
| otherwise =
" <div class=\"csl-entry\">" <> t <> "</div>"
referencesToCitation :: [Reference a] -> Citation a
referencesToCitation rs =
Citation { citationId = Nothing
, citationNoteNumber = Nothing
, citationItems = map (\r ->
CitationItem{ citationItemId = referenceId r
, citationItemLabel = Nothing
, citationItemLocator = Nothing
, citationItemType = NormalCite
, citationItemPrefix = Nothing
, citationItemSuffix = Nothing
, citationItemData = Nothing }) rs
}
-- remove >>[0] or ..[1]
removeCitationNums :: Text -> Text
removeCitationNums =
T.intercalate "\n" . map removeNum . T.lines
where
removeNum = T.dropWhile (== ' ') .
T.dropWhile (\c -> c == '>' || c == '.' ||
c == '[' || c == ']' || isDigit c)
compareTest :: CiteprocTest (CslJson Text)
-> Text
-> StateT Counts IO TestResult
compareTest test actual = do
let expected = if mode test == "citation" && isJust (citations test)
then removeCitationNums $ result test
else result test
if actual == expected
then do
modify $ \st -> st{ passed = category test : passed st }
-- suppress PASSED messages
-- liftIO $ TIO.putStrLn $ "[PASSED] " <> path test
return Passed
else do
modify $ \st -> st{ failed = category test : failed st }
liftIO $ do
TIO.putStrLn $ "[FAILED] " <> T.pack (path test)
showDiff expected actual
return $ Failed actual expected
splitSections :: ByteString -> [(Text, ByteString)]
splitSections = snd . foldl' go startingState . B.lines . removeBOM
where
removeBOM bs = if "\xef\xbb\xbf" `B.isPrefixOf` bs
then B.drop 3 bs
else bs
startingState ::
(Maybe (Text, [ByteString]), [(Text, ByteString)])
startingState = (Nothing, mempty)
go (Nothing, accum) t
| ">>==" `B.isPrefixOf` t =
let secname = T.toLower $ T.filter (\c -> isLetter c || c == '-')
$ decodeUtf8 t
in (Just (secname, mempty), accum)
| otherwise = (Nothing, accum)
go (Just (sec, buffer), accum) t
| "<<==" `B.isPrefixOf` t =
(Nothing, (sec, mconcat $ intersperse "\n" (reverse buffer)) : accum)
| otherwise = (Just (sec, t:buffer), accum)
loadTestCase :: FilePath -> IO (CiteprocTest (CslJson Text))
loadTestCase fp = do
sections <- splitSections <$> B.readFile fp
let cslBs = fromMaybe mempty $ lookup "csl" sections
let fromJSON field x =
case A.eitherDecode (L.fromStrict x) of
Left e -> error $ "JSON decoding error " <>
" in " <> fp <> " (" <>
field <> ")\n" <> show e
Right z -> z
reason <- do
exists <- doesFileExist (fp <> ".skip")
if exists
then Just <$> TIO.readFile (fp <> ".skip")
else return Nothing
return CiteprocTest
{ name = T.pack $ dropExtension $ takeBaseName fp
, path = fp
, category = T.takeWhile (/='_') $ T.pack $ takeBaseName fp
, mode = maybe mempty decodeUtf8 $ lookup "mode" sections
, result = maybe mempty decodeUtf8 $ lookup "result" sections
, csl = cslBs
, input = maybe (error "No INPUT") (fromJSON "INPUT") $
lookup "input" sections
, bibentries = fromJSON "BIBENTRIES" <$> lookup "bibentries" sections
, bibsection = fromJSON "BIBSECTION" <$> lookup "bibsection" sections
, citeItems = fromJSON "CITATION-ITEMS" <$>
lookup "citation-items" sections
, citations = removeDuplicates . fromJSON "CITATIONS" <$>
lookup "citations" sections
-- need appropriate fromjson instance:
-- fromJSON "CITATION" <$> lookup "citation-items" sections
, abbreviations = fromJSON "ABBREVIATIONS" <$>
lookup "abbreviations" sections
, skipReason = reason
, options = fromJSON "TESTOPTIONS" <$> lookup "options" sections
}
-- for motivation see e.g. test/csl/collapse_CitationNumberRangesInsert.txt
-- Later Citations can replace earlier ones with the same citationId.
removeDuplicates :: [Citation a] -> [Citation a]
removeDuplicates [] = []
removeDuplicates (c:cs) =
case citationId c of
Just cid ->
if any (\cit -> citationId cit == Just cid) cs
then removeDuplicates cs
else c : removeDuplicates cs
Nothing -> c : removeDuplicates cs
testDir :: FilePath
testDir = "test" </> "csl"
overrideDir :: FilePath
overrideDir = "test" </> "overrides"
extraDir :: FilePath
extraDir = "test" </> "extra"
main :: IO ()
main = do
args <- getArgs
let matchesPattern x =
takeExtension x == ".txt" &&
case args of
[] -> True
_ -> any (\arg -> map toLower arg `isInfixOf` map toLower x) args
overrides <- if any ('/' `elem`) args
then return []
else filter matchesPattern <$>
getDirectoryContents overrideDir
let addDir fp = if fp `elem` overrides
then overrideDir </> fp
else testDir </> fp
testFiles <- if any ('/' `elem`) args
then return args
else do
cslTests <- map addDir . filter matchesPattern
<$> getDirectoryContents testDir
extraTests <- map (extraDir </>) . filter matchesPattern
<$> getDirectoryContents extraDir
return $ cslTests ++ extraTests
testCases <- sortOn name <$> mapM loadTestCase testFiles
(_,counts) <- timeIt $
runStateT (mapM_ runTest testCases)
Counts{ failed = []
, errored = []
, passed = []
, skipped = [] }
putStrLn ""
let categories = sort $ Set.toList
$ foldr (Set.insert . category) mempty testCases
putStrLn $ printf "%-15s %6s %6s %6s %6s"
("CATEGORY" :: String)
("PASS" :: String)
("FAIL" :: String)
("ERROR" :: String)
("SKIP" :: String)
let resultsFor cat = do
let p = length . filter (== cat) . passed $ counts
let f = length . filter (== cat) . failed $ counts
let e = length . filter (== cat) . errored $ counts
let s = length . filter (== cat) . skipped $ counts
let percent = (fromIntegral p / fromIntegral (p + f + e) :: Double)
putStrLn $ printf "%-15s %6d %6d %6d %6d |%-20s|"
(T.unpack cat) p f e s
(replicate (floor (percent * 20.0)) '+')
mapM_ resultsFor categories
putStrLn $ printf "%-15s %6s %6s %6s %6s"
("-------------" :: String)
("-----" :: String)
("-----" :: String)
("-----" :: String)
("-----" :: String)
putStrLn $ printf "%-15s %6d %6d %6d %6d"
("(all)" :: String)
(length (passed counts))
(length (failed counts))
(length (errored counts))
(length (skipped counts))
case length (failed counts) + length (errored counts) of
0 -> exitSuccess
n | n <= 62 -> do
putStrLn "We have passed all the CSL tests we expect to..."
exitSuccess
| otherwise -> exitWith $ ExitFailure n
data Counts =
Counts
{ failed :: [Text]
, errored :: [Text]
, passed :: [Text]
, skipped :: [Text]
} deriving (Show)
showDiff :: Text -> Text -> IO ()
showDiff expected actual = do
-- Use this to see unicode characters (e.g. dashes) better
-- let f = mconcat . map
-- (\c -> if isAscii c
-- then T.singleton c
-- else T.pack (printf "[U+%04X]" (ord c))) . T.unpack
putStrLn $ Pretty.render $ prettyContextDiff
(Pretty.text "expected")
(Pretty.text "actual")
(Pretty.text . T.unpack)
$ getContextDiff 1 (T.lines expected) (T.lines actual)
|