packages feed

symantic-atom-0.0.0.20200523: test/Golden.hs

module Golden where

import Control.Monad (Monad(..), sequence)
import Data.Either (Either(..))
import Data.Function (($), (.))
import Data.Functor ((<$>))
import Data.Semigroup (Semigroup(..))
import Data.String (String)
import Data.Void (Void)
import System.IO (IO, FilePath)
import Text.Show (Show(..))
import qualified Data.ByteString.Lazy as BSL
import qualified Data.List as List
import qualified Data.Text.Lazy          as TL
import qualified Data.Text.Lazy.Encoding as TL

import Test.Tasty
import Test.Tasty.Golden

import qualified Symantic.XML as XML
import qualified Symantic.XML.RelaxNG as RelaxNG
import qualified Symantic.Atom as Atom

goldensIO :: IO TestTree
goldensIO =
  testGroup "Golden" <$>
  sequence
   [ goldensAtom
   ]

goldensAtom :: IO TestTree
goldensAtom = do
  inputFiles <- List.sort <$> findByExtension [".xml"] "test/Golden"
  return $ testGroup "RelaxNG"
   [ testGroup "Validate"
     [ testGolden inputFile ".read" $
      ((TL.encodeUtf8 . TL.pack . show) <$>) <$>
      XML.read Atom.format inputFile
     | inputFile <- inputFiles
     ]
   , testGroup "Compact"
     [ testGroup "Write"
       [ testGolden "test/Golden/atom" ".rnc" $
          return $ Right $ TL.encodeUtf8 $
            RelaxNG.writeRNC Atom.format
       {-
       , testGolden "test/Golden/atom" ".optim" $
          return $ Right $ TL.encodeUtf8 $ TL.pack $ show $
            XML.readOptim @XML.FileSourced @Void Atom.format
       -}
       ]
     ]
   ]

-- * Golden testing utilities
testGolden :: TestName -> TestName -> IO (Either String BSL.ByteString) -> TestTree
testGolden testName expectedExt =
  goldenVsStringDiff testName diffGolden (testName <> expectedExt)
   . (>>= unLeft)

diffGolden :: FilePath -> FilePath -> [String]
diffGolden ref new = ["diff", "-u", ref, new]

unLeft :: Either String BSL.ByteString -> IO BSL.ByteString
unLeft = \case
 Left err -> return $ TL.encodeUtf8 $ TL.pack err
 Right a  -> return a