packages feed

papa-0.7.0: test/PropertiesFS.hs

{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# OPTIONS_GHC -Wall #-}

-- | The properties of Papa's files, directories and paths.
module PropertiesFS (
  propertiesFS,
  propertiesCurrentDirectory,
) where

import qualified Control.Exception as E
import qualified Data.ByteString as SB
import qualified Data.Time as Time
import Hedgehog (Gen, Group (Group), Property, PropertyName, PropertyT, evalIO, forAll, property, withTests, (===))
import qualified Hedgehog.Gen as Gen
import qualified Hedgehog.Range as Range
import Papa
import qualified System.Directory as D
import qualified System.FilePath as F
import qualified System.IO as IO
import qualified Prelude as P

-- | The properties of Papa's files, directories and paths.
propertiesFS :: Group
propertiesFS =
  Group "papa: files, directories, paths" (directories <> files <> paths)

-- | The properties of the current directory, which is the process's: they
-- are checked one at a time, apart from all others, which they would
-- disturb.
propertiesCurrentDirectory :: Group
propertiesCurrentDirectory =
  Group "papa: the current directory" currentDirectory

prop :: PropertyName -> Property -> [(PropertyName, Property)]
prop name p =
  [(name, p)]

genName :: Gen String
genName =
  Gen.string (Range.linear 1 8) Gen.alphaNum

genNames :: Gen [String]
genNames =
  nubOrd <$> Gen.list (Range.linear 0 8) genName

-- | Any string, of the characters that matter to paths.
genPath :: Gen String
genPath =
  Gen.string (Range.linear 0 30) (Gen.frequency [(5, Gen.element ("/.\\:a b\0" :: String)), (1, Gen.unicode)])

-- | Run a property in a new, empty directory, removed afterwards.
withDir :: (FilePath -> PropertyT IO a) -> PropertyT IO a
withDir k = do
  d <- evalIO (D.getTemporaryDirectory >>= \t -> IO.openTempFile t "papa-fs" >>= \(p, h) -> IO.hClose h *> D.removeFile p *> D.createDirectory p $> p)
  a <- k d
  evalIO (D.removePathForcibly d)
  pure a

-- | Papa's action returns 'Right' what the action of "System.Directory"
-- returns, or 'Left' the 'IOException' it throws, as an 'IOFailed'.
agreesIO :: (Eq a, Show a) => IOExcept a -> IO a -> PropertyT IO ()
agreesIO papa directory = do
  p <- evalIO (runExceptT papa)
  d <- evalIO (tryIO directory)
  p === over _Left IOFailed d

tryIO :: IO a -> IO (Either IOException a)
tryIO =
  E.try

isNoSuchThing :: Either IOFailure a -> Bool
isNoSuchThing =
  either (anyOf _IOException (has _NoSuchThing . the errorType)) (const False)

directories :: [(PropertyName, Property)]
directories =
  prop "doesFileExist, doesDirectoryExist, doesPathExist agree with System.Directory" (property (do fs <- forAll genNames; ds <- forAll genNames; q <- forAll genName; withDir (\d -> do evalIO (for_ fs (\f -> D.createDirectoryIfMissing True (d </> "f") *> SB.writeFile (d </> "f" </> f) "")); evalIO (for_ ds (\x -> D.createDirectoryIfMissing True (d </> "d" </> x))); for_ ((d </> "f" </> q) : (d </> "d" </> q) : fmap ((d </> "f") </>) fs <> fmap ((d </> "d") </>) ds) (\p -> agreesIO (doesFileExist p) (D.doesFileExist p) *> agreesIO (doesDirectoryExist p) (D.doesDirectoryExist p) *> agreesIO (doesPathExist p) (D.doesPathExist p)))))
    <> prop "listDirectory: the names created, without . and .." (property (do fs <- forAll genNames; ds <- forAll genNames; withDir (\d -> do r <- evalIO (runExceptT (for_ fs (\f -> writeFile (d </> ("f" <> f)) (pack f)) *> for_ ds (\x -> createDirectory (d </> ("d" <> x))) *> listDirectory d)); fmap sort r === Right (sort (fmap ("f" <>) fs <> fmap ("d" <>) ds)))))
    <> prop "listDirectory agrees with System.Directory" (property (do n <- forAll genName; withDir (\d -> agreesIO (sort <$> listDirectory (d </> n)) (sort <$> D.listDirectory (d </> n)) *> agreesIO (sort <$> listDirectory d) (sort <$> D.listDirectory d))))
    <> prop "createDirectory: the directory, then AlreadyExists" (property (do n <- forAll genName; withDir (\d -> do r <- evalIO (runExceptT (createDirectory (d </> n) *> doesDirectoryExist (d </> n))); s <- evalIO (runExceptT (createDirectory (d </> n))); (r, either (anyOf _IOException (has _AlreadyExists . the errorType)) (const False) s) === (Right True, True))))
    <> prop "createDirectory: NoSuchThing without the parent" (property (do a <- forAll genName; b <- forAll genName; withDir (\d -> do r <- evalIO (runExceptT (createDirectory (d </> a </> b))); isNoSuchThing r === True)))
    <> prop "createDirectoryIfMissing True: every parent, and idempotent" (property (do ns <- forAll (Gen.list (Range.linear 1 5) genName); withDir (\d -> do let { p = F.joinPath (d : ns) }; r <- evalIO (runExceptT (createDirectoryIfMissing True p *> createDirectoryIfMissing True p *> doesDirectoryExist p)); r === Right True)))
    <> prop "removeDirectory: an empty directory, not a full one" (property (do n <- forAll genName; withDir (\d -> do r <- evalIO (runExceptT (createDirectory (d </> n) *> removeDirectory (d </> n) *> doesPathExist (d </> n))); s <- evalIO (runExceptT (writeFile (d </> n) (pack n) *> removeDirectory d)); (r, isLeft s) === (Right False, True))))
    <> prop "removeDirectoryRecursive: the whole tree" (property (do ns <- forAll (Gen.list (Range.linear 1 5) genName); fs <- forAll genNames; withDir (\d -> do let { p = F.joinPath (d : ns) }; let { top = F.joinPath (d : take 1 ns) }; r <- evalIO (runExceptT (createDirectoryIfMissing True p *> for_ fs (\f -> writeFile (p </> f) (pack f)) *> removeDirectoryRecursive top *> doesPathExist top)); s <- evalIO (runExceptT (removeDirectoryRecursive top)); (r, isNoSuchThing s) === (Right False, True))))
    <> prop "removePathForcibly: a missing path is not a failure" (property (do n <- forAll genName; withDir (\d -> do r <- evalIO (runExceptT (removePathForcibly (d </> n))); r === Right ())))
    <> prop "renameDirectory: moves the directory" (property (do a <- forAll genName; b <- forAll (Gen.filter (/= a) genName); withDir (\d -> do r <- evalIO (runExceptT (createDirectory (d </> a) *> renameDirectory (d </> a) (d </> b) *> traverse doesDirectoryExist [d </> a, d </> b])); r === Right [False, True])))
    <> prop "getXdgDirectory, getXdgDirectoryList, getAppUserDataDirectory agree with System.Directory" (property (do n <- forAll genName; x <- forAll (Gen.element [XdgData, XdgConfig, XdgCache, XdgState]); l <- forAll (Gen.element [XdgDataDirs, XdgConfigDirs]); agreesIO (getXdgDirectory x n) (D.getXdgDirectory x n) *> agreesIO (getXdgDirectoryList l) (D.getXdgDirectoryList l) *> agreesIO (getAppUserDataDirectory n) (D.getAppUserDataDirectory n)))
    <> prop "findExecutable, findExecutables, findFile, findFiles agree with System.Directory" (property (do n <- forAll (Gen.element ["sh", "ls", "papa-no-such-executable", ""]); fs <- forAll genNames; withDir (\d -> do evalIO (for_ fs (\f -> SB.writeFile (d </> f) "")); f <- forAll (Gen.element (n : fs)); agreesIO (findExecutable f) (D.findExecutable f) *> agreesIO (findExecutables f) (D.findExecutables f) *> agreesIO (findExecutablesInDirectories [d] f) (D.findExecutablesInDirectories [d] f) *> agreesIO (findFile [d, d] f) (D.findFile [d, d] f) *> agreesIO (findFiles [d, d] f) (D.findFiles [d, d] f))))

files :: [(PropertyName, Property)]
files =
  prop "writeFile, getFileSize: the size of the UTF-8 encoding" (property (do t <- forAll (Gen.text (Range.linear 0 50) Gen.unicode); withDir (\d -> do r <- evalIO (runExceptT (writeFile (d </> "f") t *> getFileSize (d </> "f"))); r === Right (P.toInteger (SB.length (encodeUtf8 t))))))
    <> prop "getFileSize agrees with System.Directory" (property (do n <- forAll genName; withDir (\d -> agreesIO (getFileSize (d </> n)) (D.getFileSize (d </> n)) *> agreesIO (getFileSize d) (D.getFileSize d))))
    <> prop "removeFile: the file, then NoSuchThing" (property (do n <- forAll genName; withDir (\d -> do r <- evalIO (runExceptT (writeFile (d </> n) (pack n) *> removeFile (d </> n) *> doesFileExist (d </> n))); s <- evalIO (runExceptT (removeFile (d </> n))); (r, isNoSuchThing s) === (Right False, True))))
    <> prop "renameFile, renamePath: move the contents" (property (do a <- forAll genName; b <- forAll (Gen.filter (/= a) genName); t <- forAll (Gen.text (Range.linear 0 20) Gen.unicode); withDir (\d -> do r <- evalIO (runExceptT (writeFile (d </> a) t *> renameFile (d </> a) (d </> b) *> renamePath (d </> b) (d </> a) *> ((,) <$> readFile (d </> a) <*> doesPathExist (d </> b)))); r === Right (t, False))))
    <> prop "copyFile, copyFileWithMetadata: the contents, and the source kept" (property (do t <- forAll (Gen.text (Range.linear 0 20) Gen.unicode); m <- forAll Gen.bool; withDir (\d -> do r <- evalIO (runExceptT (writeFile (d </> "a") t *> bool copyFile copyFileWithMetadata m (d </> "a") (d </> "b") *> ((,) <$> readFile (d </> "a") <*> readFile (d </> "b")))); r === Right (t, t))))
    <> prop "copyFile: NoSuchThing without the source" (property (do n <- forAll genName; withDir (\d -> do r <- evalIO (runExceptT (copyFile (d </> n) (d </> "b"))); isNoSuchThing r === True)))
    <> prop "setModificationTime, setAccessTime: read back" (property (do s <- forAll (Gen.integral (Range.linear 0 2000000000)); withDir (\d -> do let { t = Time.addUTCTime (P.fromInteger s) (Time.UTCTime (Time.fromGregorian 1970 1 1) 0) }; r <- evalIO (runExceptT (writeFile (d </> "f") (pack "") *> setModificationTime (d </> "f") t *> setAccessTime (d </> "f") t *> ((,) <$> getModificationTime (d </> "f") <*> getAccessTime (d </> "f")))); r === Right (t, t))))
    <> prop "getModificationTime, getAccessTime: NoSuchThing for a missing file" (property (do n <- forAll genName; withDir (\d -> do r <- evalIO (runExceptT (getModificationTime (d </> n))); s <- evalIO (runExceptT (getAccessTime (d </> n))); (isNoSuchThing r, isNoSuchThing s) === (True, True))))
    <> prop "setPermissions: System.Directory's, and executable read back (writable is always True for root)" (property (do w <- forAll Gen.bool; x <- forAll Gen.bool; withDir (\d -> do let { perms q = setOwnerReadable True (setOwnerWritable w (setOwnerExecutable x q)) }; r <- evalIO (runExceptT (writeFile (d </> "f") (pack "") *> getPermissions (d </> "f") >>= \p -> setPermissions (d </> "f") (perms p) *> getPermissions (d </> "f"))); s <- evalIO (IO.writeFile (d </> "g") "" *> D.getPermissions (d </> "g") >>= \p -> D.setPermissions (d </> "g") (perms p) *> D.getPermissions (d </> "g")); (r, fmap (\p -> (readable p, executable p)) r) === (Right s, Right (True, x)))))
    <> prop "copyPermissions: the permissions of the source" (property (do x <- forAll Gen.bool; withDir (\d -> do r <- evalIO (runExceptT (writeFile (d </> "a") (pack "") *> writeFile (d </> "b") (pack "") *> getPermissions (d </> "a") >>= \p -> setPermissions (d </> "a") (setOwnerExecutable x p) *> copyPermissions (d </> "a") (d </> "b") *> getPermissions (d </> "b"))); fmap executable r === Right x)))
    <> prop "createFileLink, createDirectoryLink, getSymbolicLinkTarget, pathIsSymbolicLink, removeDirectoryLink" (property (do n <- forAll genName; withDir (\d -> do r <- evalIO (runExceptT (writeFile (d </> "f") (pack n) *> createDirectory (d </> "d") *> createFileLink (d </> "f") (d </> "fl") *> createDirectoryLink (d </> "d") (d </> "dl") *> ((,,,) <$> traverse pathIsSymbolicLink [d </> "f", d </> "fl", d </> "dl"] <*> getSymbolicLinkTarget (d </> "fl") <*> readFile (d </> "fl") <*> (removeDirectoryLink (d </> "dl") *> traverse doesPathExist [d </> "dl", d </> "d"])))); r === Right ([False, True, True], d </> "f", pack n, [False, True]))))

paths :: [(PropertyName, Property)]
paths =
  prop "filepath: total at every string" (property (do p <- forAll genPath; q <- forAll genPath; r <- evalIO (E.try (E.evaluate (length (concat [show (splitPath p, splitDirectories p, splitFileName p, splitExtension p, splitExtensions p, splitDrive p), show (normalise p, makeValid p, isValid p, takeDirectory p, takeBaseName p, takeExtension p, dropExtension p), show (p </> q, p -<.> q, addExtension p q, replaceExtension p q, makeRelative p q, equalFilePath p q, stripExtension q p, isExtensionOf q p), show (splitSearchPath p, hasTrailingPathSeparator p, dropTrailingPathSeparator p, addTrailingPathSeparator p)])))); either (\(_ :: E.SomeException) -> False) (const True) r === True))
    <> prop "filepath: splitExtension, splitExtensions, splitDrive and splitPath rebuild the path" (property (do p <- forAll genPath; (uncurry (<>) (splitExtension p), uncurry (<>) (splitExtensions p), uncurry (<>) (splitDrive p), concat (splitPath p)) === (p, p, p, p)))
    <> prop "filepath: they are System.FilePath's" (property (do p <- forAll genPath; q <- forAll genPath; (p </> q, splitPath p, normalise p, p -<.> q) === (p F.</> q, F.splitPath p, F.normalise p, p F.-<.> q)))
    <> prop "getSearchPath agrees with System.FilePath" (withTests 10 (property (agreesIO getSearchPath F.getSearchPath)))

currentDirectory :: [(PropertyName, Property)]
currentDirectory =
  prop "withCurrentDirectory: runs in the directory, then returns, whether or not the action fails" (withTests 20 (property (do b <- forAll Gen.bool; withDir (\d -> do c <- evalIO D.getCurrentDirectory; r <- evalIO (runExceptT (withCurrentDirectory d (getCurrentDirectory >>= \x -> bool (pure x) (removeFile "papa-no-such-file" $> x) b))); c' <- evalIO D.getCurrentDirectory; d' <- evalIO (D.canonicalizePath d); (bool (preview _Right r) Nothing b, isLeft r, c') === (bool (Just d') Nothing b, b, c)))))
    <> prop "withCurrentDirectory: a missing directory is a failure" (property (do n <- forAll genName; withDir (\d -> do r <- evalIO (runExceptT (withCurrentDirectory (d </> n) (pure ()))); isNoSuchThing r === True)))
    <> prop "getCurrentDirectory, getHomeDirectory, getTemporaryDirectory, getUserDocumentsDirectory agree with System.Directory" (withTests 10 (property (agreesIO getCurrentDirectory D.getCurrentDirectory *> agreesIO getHomeDirectory D.getHomeDirectory *> agreesIO getTemporaryDirectory D.getTemporaryDirectory *> agreesIO getUserDocumentsDirectory D.getUserDocumentsDirectory)))
    <> prop "canonicalizePath, makeAbsolute, makeRelativeToCurrentDirectory agree with System.Directory" (property (do p <- forAll genPath; agreesIO (canonicalizePath p) (D.canonicalizePath p) *> agreesIO (makeAbsolute p) (D.makeAbsolute p) *> agreesIO (makeRelativeToCurrentDirectory p) (D.makeRelativeToCurrentDirectory p)))