Skip to content

Commit

Permalink
New RECREATE_GOLDEN_FILES which will causes golden tests to always cr…
Browse files Browse the repository at this point in the history
…eate golden files replacing any existing golden files
  • Loading branch information
newhoggy committed Jan 3, 2024
1 parent 0016f0b commit 8cab49d
Showing 1 changed file with 17 additions and 7 deletions.
24 changes: 17 additions & 7 deletions src/Hedgehog/Extras/Test/Golden.hs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -75,8 +82,10 @@ diffVsGoldenFile actualContent referenceFile = GHC.withFrozenCallStack $ do

fileExists <- liftIO $ IO.doesFileExist referenceFile

if fileExists
if fileExists && 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
Expand All @@ -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"
Expand Down

0 comments on commit 8cab49d

Please sign in to comment.