tasty-mgolden (empty) → 0.0.1
raw patch · 6 files changed
+341/−0 lines, 6 filesdep +Diffdep +basedep +filepath
Dependencies added: Diff, base, filepath, hlint, tasty, tasty-expected-failure, tasty-hunit, tasty-mgolden, text, typed-process
Files
- LICENSE +11/−0
- example/Test.hs +8/−0
- src/Test/Tasty/MGolden.hs +136/−0
- tasty-mgolden.cabal +112/−0
- test/HLint.hs +10/−0
- test/Test.hs +64/−0
+ LICENSE view
@@ -0,0 +1,11 @@+Copyright 2019-2020 Markus Schirp++Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:++1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.++2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.++3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ example/Test.hs view
@@ -0,0 +1,8 @@+import Test.Tasty+import Test.Tasty.MGolden++main :: IO ()+main = defaultMain $ testGroup "golden tests"+ [ goldenTest "example-a" "example/example-a.txt" $ pure "foo\nbar\n"+ , goldenTest "example-b" "example/example-b.txt" $ pure "foo\nbaz\n"+ ]
+ src/Test/Tasty/MGolden.hs view
@@ -0,0 +1,136 @@+{- | Golden testing provider for 'tasty'++This module implements the [golden testing pattern](https://ro-che.info/articles/2017-12-04-golden-tests).++-}++module Test.Tasty.MGolden (Mode(..), goldenTest, printDetails) where++import Control.Applicative (empty)+import Prelude hiding (print, putStrLn)+import Data.Foldable (traverse_)+import Data.Proxy (Proxy(..))+import Data.Text (Text)+import Data.Typeable (Typeable)+import Test.Tasty+import Test.Tasty.Options+import Test.Tasty.Providers+import Test.Tasty.Providers.ConsoleFormat++import qualified Data.Algorithm.Diff as Diff+import qualified Data.Text as Text+import qualified Data.Text.IO as Text+import qualified System.IO.Error as Error++-- | Golden test run mode+data Mode+ = RunTest -- ^ Run the tests, error (with diff) on actual vs expectation mismatch+ | UpdateExpected -- ^ Run the tests, update the expectation on actual vs expectation mismatch+ deriving stock (Eq, Ord, Typeable, Show)++instance IsOption Mode where+ defaultValue = RunTest+ parseValue = \case+ "test" -> pure RunTest+ "update" -> pure UpdateExpected+ _other -> empty++ optionName = pure "update"+ optionHelp = pure "Update expected on mismatched example"+ optionCLParser = flagCLParser empty UpdateExpected++data Golden = Golden+ { action :: IO Text+ , expectedPath :: FilePath+ }+ deriving stock Typeable++instance IsTest Golden where+ run options golden _callback = runGolden golden options+ testOptions = pure . pure $ Option (Proxy :: Proxy Mode)++-- | Define a golden test+goldenTest+ :: String -- ^ Name of the test+ -> FilePath -- ^ Path of the expectation file+ -> IO Text -- ^ Test action+ -> TestTree+goldenTest name expectedPath action = singleTest name Golden{..}++runGolden :: Golden -> OptionSet -> IO Result+runGolden golden@Golden{..} options = do+ actual <- action++ maybe+ (absentFile golden options actual)+ (testExpected golden options actual)+ =<< tryRead expectedPath++absentFile :: Golden -> OptionSet -> Text -> IO Result+absentFile golden@Golden{..} options actual =+ if shouldUpdate options+ then updateExpected golden actual+ else pure $ testFailed "file is absent"++testExpected :: Golden -> OptionSet -> Text -> Text -> IO Result+testExpected golden@Golden{..} options actual expected =+ if expected == actual+ then pure $ testPassed empty+ else mismatch options golden expected actual++mismatch :: OptionSet -> Golden -> Text -> Text -> IO Result+mismatch options golden expected actual =+ if shouldUpdate options+ then updateExpected golden actual+ else pure . testFailedDetails empty $ printDetails Text.putStrLn expected actual++updateExpected :: Golden -> Text -> IO Result+updateExpected Golden{..} actual = do+ Text.writeFile expectedPath actual+ pure $ testPassed "UPDATE"++printDetails :: (Text -> IO ()) -> Text -> Text -> ResultDetailsPrinter+printDetails putStrLn expected actual = ResultDetailsPrinter print+ where+ print :: Int -> (ConsoleFormat -> IO () -> IO ()) -> IO ()+ print _indent formatter+ = traverse_ printDiff+ $ Diff.getGroupedDiff (Text.lines expected) (Text.lines actual)+ where+ printDiff :: Diff.Diff [Text] -> IO ()+ printDiff = \case+ (Diff.Both line _) -> printLines ' ' neutralFormat line+ (Diff.First line) -> printLines '-' removeFormat line+ (Diff.Second line) -> printLines '+' addFormat line++ printLines :: Char -> ConsoleFormat -> [Text] -> IO ()+ printLines prefix format lines'+ = formatter format+ $ traverse_ printLine lines'+ where+ printLine :: Text -> IO ()+ printLine line = putStrLn $ Text.singleton prefix <> line++addFormat :: ConsoleFormat+addFormat = okFormat++neutralFormat :: ConsoleFormat+neutralFormat = infoOkFormat++removeFormat :: ConsoleFormat+removeFormat = infoFailFormat++shouldUpdate :: OptionSet -> Bool+shouldUpdate options = (lookupOption options :: Mode) == UpdateExpected++tryRead :: FilePath -> IO (Maybe Text)+tryRead path =+ Error.catchIOError+ (pure <$> Text.readFile path)+ handler+ where+ handler :: Error.IOError -> IO (Maybe Text)+ handler error' =+ if Error.isDoesNotExistError error'+ then pure empty+ else Error.ioError error'
+ tasty-mgolden.cabal view
@@ -0,0 +1,112 @@+cabal-version: 1.12++-- This file has been generated from package.yaml by hpack version 0.33.0.+--+-- see: https://github.com/sol/hpack+--+-- hash: e4c5b3bd31a278700368fd88f0680bf44bebc943630afe0e6c01bdc095db8619++name: tasty-mgolden+version: 0.0.1+synopsis: Golden testing provider for tasty with muti-line diff output+description: Please visit the README at <https://github.com/mbj/tasty-mgolden#readme>+ for usage information.+category: Testing+homepage: https://github.com/mbj/tasty-mgolden#readme+bug-reports: https://github.com/mbj/tasty-mgolden/issues+author: Markus Schirp <mbj@schirp-dso.com>+maintainer: Markus Schirp <mbj@schirp-dso.com>+license: BSD3+license-file: LICENSE+tested-with: GHC ==8.6.5 || ==8.8.3+build-type: Simple++source-repository head+ type: git+ location: https://github.com/mbj/tasty-mgolden++flag development+ description: Run GHC with development flags+ manual: True+ default: False++library+ exposed-modules:+ Test.Tasty.MGolden+ other-modules:+ Paths_tasty_mgolden+ hs-source-dirs:+ src+ default-extensions: DerivingStrategies LambdaCase NoImplicitPrelude OverloadedStrings RecordWildCards StrictData+ ghc-options: -Wall -Wcompat -Widentities -Wimplicit-prelude -Wincomplete-record-updates -Wincomplete-uni-patterns -Wmissing-exported-signatures -Wmissing-local-signatures -Wmonomorphism-restriction -Wredundant-constraints -funbox-strict-fields+ build-depends:+ Diff ==0.3.4 || >=0.4 && <0.5+ , base >=4.12 && <=4.15+ , filepath >=1.4.2 && <1.5+ , tasty >=1.3.1 && <1.4+ , text >=1.2 && <1.3+ if flag(development)+ ghc-options: -Werror+ else+ ghc-options: -Wwarn+ default-language: Haskell2010++executable tasty-mgolden-example+ main-is: example/Test.hs+ default-extensions: DerivingStrategies LambdaCase NoImplicitPrelude OverloadedStrings RecordWildCards StrictData ImplicitPrelude+ ghc-options: -Wall -Wcompat -Widentities -Wimplicit-prelude -Wincomplete-record-updates -Wincomplete-uni-patterns -Wmissing-exported-signatures -Wmissing-local-signatures -Wmonomorphism-restriction -Wredundant-constraints -funbox-strict-fields -rtsopts -threaded -with-rtsopts=-N -Wno-implicit-prelude+ build-depends:+ Diff ==0.3.4 || >=0.4 && <0.5+ , base >=4.12 && <=4.15+ , filepath >=1.4.2 && <1.5+ , tasty >=1.3.1 && <1.4+ , tasty-expected-failure+ , tasty-hunit+ , tasty-mgolden+ , text >=1.2 && <1.3+ if flag(development)+ ghc-options: -Werror+ else+ ghc-options: -Wwarn+ default-language: Haskell2010++test-suite golden+ type: exitcode-stdio-1.0+ main-is: test/Test.hs+ default-extensions: DerivingStrategies LambdaCase NoImplicitPrelude OverloadedStrings RecordWildCards StrictData+ ghc-options: -Wall -Wcompat -Widentities -Wimplicit-prelude -Wincomplete-record-updates -Wincomplete-uni-patterns -Wmissing-exported-signatures -Wmissing-local-signatures -Wmonomorphism-restriction -Wredundant-constraints -funbox-strict-fields -rtsopts -threaded -with-rtsopts=-N+ build-depends:+ Diff ==0.3.4 || >=0.4 && <0.5+ , base >=4.12 && <=4.15+ , filepath >=1.4.2 && <1.5+ , tasty >=1.3.1 && <1.4+ , tasty-expected-failure+ , tasty-hunit+ , tasty-mgolden+ , text >=1.2 && <1.3+ , typed-process+ if flag(development)+ ghc-options: -Werror+ else+ ghc-options: -Wwarn+ default-language: Haskell2010++test-suite hlint+ type: exitcode-stdio-1.0+ main-is: HLint.hs+ hs-source-dirs:+ test+ default-extensions: DerivingStrategies LambdaCase NoImplicitPrelude OverloadedStrings RecordWildCards StrictData+ ghc-options: -Wall -Wcompat -Widentities -Wimplicit-prelude -Wincomplete-record-updates -Wincomplete-uni-patterns -Wmissing-exported-signatures -Wmissing-local-signatures -Wmonomorphism-restriction -Wredundant-constraints -funbox-strict-fields -rtsopts -threaded -with-rtsopts=-N+ build-depends:+ Diff ==0.3.4 || >=0.4 && <0.5+ , base >=4.12 && <=4.15+ , filepath >=1.4.2 && <1.5+ , hlint+ , tasty >=1.3.1 && <1.4+ , text >=1.2 && <1.3+ if flag(development)+ ghc-options: -Werror+ else+ ghc-options: -Wwarn+ default-language: Haskell2010
+ test/HLint.hs view
@@ -0,0 +1,10 @@+import Control.Monad (unless)+import Data.List (null)+import Language.Haskell.HLint3 (hlint)+import System.Exit (exitFailure)+import System.IO (IO)++main :: IO ()+main = do+ hints <- hlint ["."]+ unless (null hints) exitFailure
+ test/Test.hs view
@@ -0,0 +1,64 @@+import Data.IORef+import Data.Text (Text)+import Prelude+import Test.Tasty+import Test.Tasty.ExpectedFailure+import Test.Tasty.HUnit+import Test.Tasty.MGolden+import Test.Tasty.Providers.ConsoleFormat++import qualified Data.Text.IO as Text+import qualified System.Exit as Exit+import qualified System.Process.Typed as Process++main :: IO ()+main = defaultMain tests++tests :: TestTree+tests = testGroup "mgolden tests"+ [ goldenTest path path $ pure "foo\nbar\n"+ , expectFail $ goldenTest path path $ pure "foo\nbaz\n"+ , testFormat+ , testWorkflow+ ]+ where+ path :: String+ path = "test/expected/example.txt"++testFormat :: TestTree+testFormat = testCase "diff format" $ do+ ioRef <- newIORef id+ runPrinter $ printDetails (fakePutStrLn ioRef) "foo\nbar" "foo\nbaz"+ assertEqual "expected diff format" [" foo", "-bar", "+baz"] =<< readPuts ioRef++fakePutStrLn :: IORef ([Text] -> [Text]) -> Text -> IO ()+fakePutStrLn ioRef text =+ modifyIORef ioRef $ \current -> current . (text :)++readPuts :: IORef ([Text] -> [Text]) -> IO [Text]+readPuts ioRef = ($ []) <$> readIORef ioRef++runPrinter :: ResultDetailsPrinter -> IO ()+runPrinter (ResultDetailsPrinter action) = action 0 (const id)++testWorkflow :: TestTree+testWorkflow =+ testCase "usage workflow" $ do+ reset+ assertEqual "initialy exits with tatus 1" (Exit.ExitFailure 1) =<< run []+ assertEqual "exits 0 with update flag" Exit.ExitSuccess =<< run ["--update"]+ assertEqual "has updated contents" "foo\nbaz\n" =<< Text.readFile "example/example-b.txt"+ reset++run :: [String] -> IO Exit.ExitCode+run arguments = do+ (status, _, _) <-+ Process.readProcess+ $ Process.proc "stack"+ (["exec", "--", "tasty-mgolden-example"] <> arguments)+ pure status++reset :: IO ()+reset = do+ Text.writeFile "example/example-a.txt" "foo\nbar"+ Text.writeFile "example/example-b.txt" "foo\nbar"