From 7df40ca57e40f80c00db40f4d3d0fceb8348c850 Mon Sep 17 00:00:00 2001 From: John Ky Date: Wed, 3 Jan 2024 20:47:22 +1100 Subject: [PATCH] New RECREATE_GOLDEN_FILES which will causes golden tests to always create golden files replacing any existing golden files --- src/Hedgehog/Extras/Test/Golden.hs | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/src/Hedgehog/Extras/Test/Golden.hs b/src/Hedgehog/Extras/Test/Golden.hs index 25026c66..0c486ff0 100644 --- a/src/Hedgehog/Extras/Test/Golden.hs +++ b/src/Hedgehog/Extras/Test/Golden.hs @@ -49,10 +49,17 @@ createFiles = IO.unsafePerformIO $ do value <- IO.lookupEnv "CREATE_GOLDEN_FILES" return $ value == Just "1" +-- | Whether the test should create the golden files if the file does ont exist. +recreateFiles :: Bool +recreateFiles = IO.unsafePerformIO $ do + value <- IO.lookupEnv "RECREATE_GOLDEN_FILES" + return $ value == Just "1" + -- | Diff contents against the golden file. If CREATE_GOLDEN_FILES environment is --- set to "1", then should the gold file not exist it would be created. If --- GOLDEN_FILE_LOG_FILE is set to a filename, then the golden file path will be --- logged to the specified file. +-- set to "1", then should the golden file not exist it would be created. If +-- RECREATE_GOLDEN_FILES is set to "1", then should the golden file exist it would +-- be recreated. If GOLDEN_FILE_LOG_FILE is set to a filename, then the golden file +-- path will be logged to the specified file. -- -- Set the environment variable when you intend to generate or re-generate the golden -- file for example when running the test for the first time or if the golden file @@ -75,8 +82,10 @@ diffVsGoldenFile actualContent referenceFile = GHC.withFrozenCallStack $ do fileExists <- liftIO $ IO.doesFileExist referenceFile - if fileExists + if fileExists && (createFiles || not recreateFiles) then do + -- RECREATE_GOLDEN_FILES is not set so we compare the actual content against + -- the golden file. referenceLines <- List.lines <$> H.readFile referenceFile let difference = getGroupedDiff actualLines referenceLines case difference of @@ -85,14 +94,15 @@ diffVsGoldenFile actualContent referenceFile = GHC.withFrozenCallStack $ do _ -> do H.note_ $ "Golden test failed against golden file: " <> referenceFile failMessage callStack $ ppDiff difference - else if createFiles + else if createFiles || recreateFiles then do - -- CREATE_GOLDEN_FILES is set, so we create any golden files that don't - -- already exist. + -- Either CREATE_GOLDEN_FILES or RECREATE_GOLDEN_FILES is set, so we create any + -- golden files that don't already exist. H.note_ $ "Creating golden file " <> referenceFile H.createDirectoryIfMissing_ (takeDirectory referenceFile) H.writeFile referenceFile actualContent else do + -- Neither CREATE_GOLDEN_FILES nor RECREATE_GOLDEN_FILES is set, so we fail H.note_ $ mconcat [ "Golden file " <> referenceFile , " does not exist. To create, run with CREATE_GOLDEN_FILES=1"