packages feed

libheif-hs-0.2.0.0: test/Main.hs

{-# LANGUAGE CPP #-}

module Main (main) where

import Codec.HEIF
import Control.Monad
import Data.ByteString.Lazy qualified as BSL
import System.Directory (doesFileExist)
import System.IO.Temp (withSystemTempFile)
import Test.Hspec

main :: IO ()
main = hspec spec

isHEIFException :: HeifError -> HeifSubError -> HeifException -> Bool
isHEIFException expectedCode expectedSubcode (LibraryException (Library {..})) =
  code == expectedCode && subcode == expectedSubcode
isHEIFException _ _ _ = False

spec :: Spec
spec = describe "libheif-hs tests" $ do
  describe "HEIF library inclusion" $ do
    it "The linked library version is non empty" $ do
      x <- heifVersion
      x `shouldNotBe` ""
    describe "Image RGB decoding" $ do
      it "Fails with an empty image" $ do
        decodeThrow defaultDecodeOptions mempty
          `shouldThrow` isHEIFException HeifErrorInvalidInput HeifSubErrorUnspecified
    forM_
      [ (HEVC, "./samples/heic-100x100.heic"),
        (AV1, "./samples/01-blue-sky.avif")
      ]
      $ \(format, sampleFile) ->
        describe (unwords [show format, "format"]) $ do
          it "Can decode file" $ do
            doesFileExist sampleFile >>= (`shouldBe` True)
            decoded <- decodeFromFileThrow defaultDecodeOptions sampleFile
            encoded <- encodeThrow defaultEncodeOptions {eoFormat = format} decoded
            decoded' <- decodeThrow defaultDecodeOptions $ BSL.toStrict encoded
            decodedMetadata decoded `shouldBe` decodedMetadata decoded'
            let image = decodedImage decoded
                image' = decodedImage decoded'
            imageWidth image `shouldBe` imageWidth image'
            imageHeight image `shouldBe` imageHeight image'
          it "Can encode to file" $ do
            withSystemTempFile "test-libheif-hs" $ \testFile _ -> do
              decoded <- decodeFromFileThrow defaultDecodeOptions sampleFile
              encodeToFileThrow defaultEncodeOptions {eoFormat = format} testFile decoded
              doesFileExist testFile >>= (`shouldBe` True)