packages feed

dag-migrations-0.1.0.0 / test / Database / DagMigrations / PlanSpec.hs

module Database.DagMigrations.PlanSpec (spec) whereimport Control.Monad (forM_)import Data.Functor.Identity (Identity)import Data.List qualified as Listimport Data.List.NonEmpty (NonEmpty (..))import Data.List.NonEmpty qualified as NonEmptyimport Data.Map.Strict qualified as Mapimport Data.Set (Set)import Data.Set qualified as Setimport Data.Text (Text)import Database.DagMigrations.Error (Direction (..), FingerprintMismatch (..), PlanError (..))import Database.DagMigrations.Genimport Database.DagMigrations.Graphimport Database.DagMigrations.Migration (Fingerprint (..), Migration (..))import Database.DagMigrations.Planimport Hedgehog (Gen, PropertyT, annotateShow, failure)import Hedgehog.Gen qualified as Genimport Test.Hspecimport Test.Hspec.Hedgehog (assert, forAll, hedgehog, (===))spec :: Specspec = do  describe "plan Up" $ do    it "orders steps by the linear extension of the whole registry" $      case validate [testMigration "1" ["3"], testMigration "2" [], testMigration "3" []] of        Left errors -> expectationFailure (show errors)        Right graph ->          fmap planIdentifiers (plan defaultPlanOptions graph (Set.fromList ["3"]) Up AllMigrations)            `shouldBe` Right ["2", "1"]    it "applies the target's down-set minus the applied set: the join S ∪ ↓t" $ hedgehog $ do      (graph, applied, target) <- genCase      steps <- planned graph applied Up target      Set.fromList steps === Set.difference (upTargetSet graph target) applied      Set.union applied (Set.fromList steps) === Set.union applied (upTargetSet graph target)    it "puts every step after its dependencies" $ hedgehog $ do      (graph, applied, target) <- genCase      steps <- planned graph applied Up target      let prefixes = List.inits steps      forM_ (zip steps prefixes) $ \(step, earlier) ->        assert (dependenciesOf graph step `Set.isSubsetOf` Set.union applied (Set.fromList earlier))    it "keeps the applied set a down-set after every prefix" $ hedgehog $ do      (graph, applied, target) <- genCase      steps <- planned graph applied Up target      assert (all (isDownSet graph . Set.union applied . Set.fromList) (List.inits steps))    it "plans nothing after the plan is applied" $ hedgehog $ do      (graph, applied, target) <- genCase      steps <- planned graph applied Up target      again <- planned graph (Set.union applied (Set.fromList steps)) Up target      again === []    it "lists steps in the order of linearOrder" $ hedgehog $ do      (graph, applied, target) <- genCase      steps <- planned graph applied Up target      steps === filter (`elem` steps) (linearOrder graph)    it "does not depend on the order of registration" $ hedgehog $ do      specs <- forAll genRegistry      shuffled <- forAll (Gen.shuffle specs)      graph <- validated (toRegistry specs)      graph' <- validated (toRegistry shuffled)      applied <- forAll (genDownSet graph)      target <- forAll (genTarget graph)      steps <- planned graph applied Up target      steps' <- planned graph' applied Up target      steps === steps'  describe "plan Down" $ do    it "reverts the meet S ∩ (P ∖ (↑t ∖ {t})), keeping the target applied" $ hedgehog $ do      (graph, applied, target) <- genCase      steps <- planned graph applied Down target      Set.difference applied (Set.fromList steps) === Set.intersection applied (downTargetSet graph target)    it "keeps the applied set a down-set after every prefix, and the target applied" $ hedgehog $ do      (graph, applied, target) <- genCase      steps <- planned graph applied Down target      assert (all (isDownSet graph . Set.difference applied . Set.fromList) (List.inits steps))      case target of        TargetMigration t -> assert (t `notElem` steps)        AllMigrations -> pure ()    it "plans nothing after the plan is applied" $ hedgehog $ do      (graph, applied, target) <- genCase      steps <- planned graph applied Down target      again <- planned graph (Set.difference applied (Set.fromList steps)) Down target      again === []    it "does not depend on the order of registration" $ hedgehog $ do      specs <- forAll genRegistry      shuffled <- forAll (Gen.shuffle specs)      graph <- validated (toRegistry specs)      graph' <- validated (toRegistry shuffled)      applied <- forAll (genDownSet graph)      target <- forAll (genTarget graph)      steps <- planned graph applied Down target      steps' <- planned graph' applied Down target      steps === steps'    it "lists steps in the reverse order of linearOrder" $ hedgehog $ do      (graph, applied, target) <- genCase      steps <- planned graph applied Down target      steps === reverse (filter (`elem` steps) (linearOrder graph))    it "is undone by applying every migration" $ hedgehog $ do      (graph, applied, target) <- genCase      reverted <- planned graph applied Down target      let afterDown = Set.difference applied (Set.fromList reverted)      restored <- planned graph afterDown Up AllMigrations      Set.union afterDown (Set.fromList restored) === registeredIdentifiers graph    it "reports every irreversible migration, and reverts nothing" $ hedgehog $ do      specs <- forAll genRegistry      irreversible <- forAll (Set.fromList <$> Gen.subsequence (map fst specs))      let marked =            [ if Set.member (migrationId m) irreversible then m {migrationDown = Nothing} else m            | m <- toRegistry specs            ]      graph <- validated marked      applied <- forAll (genDownSet graph)      target <- forAll (genTarget graph)      let reverting = Set.difference applied (downTargetSet graph target)          blocked = Set.intersection reverting irreversible      case plan defaultPlanOptions graph applied Down target of        Right (Plan _ steps) -> do          assert (Set.null blocked)          length steps === Set.size reverting        Left errors -> NonEmpty.toList errors === map Irreversible (reverse (filter (`Set.member` blocked) (linearOrder graph)))  describe "plan errors" $ do    it "reports an unknown target" $      planErrors [testMigration "a" []] Set.empty (TargetMigration "zz")        `shouldBe` Just (UnknownTarget "zz" :| [])    it "reports an applied identifier that is not registered, unless allowed" $ do      planErrors [testMigration "a" []] (Set.fromList ["old"]) AllMigrations        `shouldBe` Just (UnregisteredApplied "old" :| [])      case validate [testMigration "a" []] of        Left errors -> expectationFailure (show errors)        Right graph ->          fmap planIdentifiers (plan (PlanOptions True) graph (Set.fromList ["old"]) Up AllMigrations)            `shouldBe` Right ["a"]    it "reports every error of the first phase at once, in check order" $      planErrors [testMigration "a" [], testMigration "b" ["a"]] (Set.fromList ["old", "b"]) (TargetMigration "zz")        `shouldBe` Just (UnregisteredApplied "old" :| [InconsistentApplied "b" "a", UnknownTarget "zz"])    it "leaves allowed unregistered identifiers applied under Down" $      case validate [testMigration "a" [], testMigration "b" ["a"]] of        Left errors -> expectationFailure (show errors)        Right graph ->          fmap planIdentifiers (plan (PlanOptions True) graph (Set.fromList ["old", "a", "b"]) Down AllMigrations)            `shouldBe` Right ["b", "a"]    it "reports an applied set that is not a down-set" $      planErrors [testMigration "a" [], testMigration "b" ["a"]] (Set.fromList ["b"]) AllMigrations        `shouldBe` Just (InconsistentApplied "b" "a" :| [])    it "reports an inconsistency exactly when the applied set is not a down-set" $ hedgehog $ do      specs <- forAll genRegistry      graph <- validated (toRegistry specs)      applied <- forAll (Set.fromList <$> Gen.subsequence (map fst specs))      let inconsistent = case plan defaultPlanOptions graph applied Up AllMigrations of            Left errors -> any isInconsistentApplied errors            Right _ -> False      inconsistent === not (isDownSet graph applied)  describe "status" $    it "lists registered migrations in order, with flags, and the unregistered applied ones" $      case validate [testMigration "a" [], testMigration "b" ["a"]] of        Left errors -> expectationFailure (show errors)        Right graph ->          status graph (Set.fromList ["a", "old"])            `shouldBe` ([("a", True), ("b", False)], Set.fromList ["old"])  describe "checkFingerprints" $ do    it "records on first use, and reports both kinds of mismatch" $ do      let withFingerprint name fingerprint = (testMigration name []) {migrationFingerprint = fingerprint}          v1 = Fingerprint "v1"          v2 = Fingerprint "v2"      case validate        [ withFingerprint "first-use" (Just v1),          withFingerprint "changed" (Just v2),          withFingerprint "removed" Nothing,          withFingerprint "same" (Just v1),          withFingerprint "none" Nothing        ] of        Left errors -> expectationFailure (show errors)        Right graph ->          checkFingerprints            graph            ( Map.fromList                [ ("first-use", Nothing),                  ("changed", Just v1),                  ("removed", Just v1),                  ("same", Just v1),                  ("none", Nothing),                  ("unregistered", Just v1)                ]            )            `shouldBe` ( Map.fromList [("first-use", v1)],                         [ FingerprintMismatch "changed" (Just v1) (Just v2),                           FingerprintMismatch "removed" (Just v1) Nothing                         ]                       )  where    planErrors :: [TestMigration] -> Set Text -> Target Text -> Maybe (NonEmpty (PlanError Text))    planErrors registry applied target = case validate registry of      Left _ -> Nothing      Right graph -> either Just (const Nothing) (plan defaultPlanOptions graph applied Up target)-- | 'AllMigrations', or a registered migration when the graph has one.genTarget :: MigrationGraph Text m -> Gen (Target Text)genTarget graph = case linearOrder graph of  [] -> pure AllMigrations  ids -> Gen.choice [pure AllMigrations, TargetMigration <$> Gen.element ids]-- | A valid graph, a down-set of it, and a target.genCase :: PropertyT IO (MigrationGraph Text Identity, Set Text, Target Text)genCase = do  specs <- forAll genRegistry  graph <- validated (toRegistry specs)  applied <- forAll (genDownSet graph)  target <- forAll (genTarget graph)  pure (graph, applied, target)-- | The identifiers of the plan, or a test failure that shows the errors.planned :: MigrationGraph Text m -> Set Text -> Direction -> Target Text -> PropertyT IO [Text]planned graph applied direction target =  case plan defaultPlanOptions graph applied direction target of    Left errors -> annotateShow errors >> failure    Right p -> pure (planIdentifiers p)-- | The set that 'Up' brings in: every registered migration, or the-- target's down-set.upTargetSet :: MigrationGraph Text m -> Target Text -> Set TextupTargetSet graph AllMigrations = registeredIdentifiers graphupTargetSet graph (TargetMigration t) = downSet graph t-- | The largest down-set that a 'Down' plan leaves applied: nothing, or-- everything except what depends on the target.downTargetSet :: MigrationGraph Text m -> Target Text -> Set TextdownTargetSet _ AllMigrations = Set.emptydownTargetSet graph (TargetMigration t) =  Set.difference (registeredIdentifiers graph) (Set.delete t (upSet graph t))isInconsistentApplied :: PlanError i -> BoolisInconsistentApplied (InconsistentApplied _ _) = TrueisInconsistentApplied _ = FalsedependenciesOf :: MigrationGraph Text m -> Text -> Set TextdependenciesOf graph i = maybe Set.empty migrationDependencies (lookupMigration i graph)