|
| 1 | +module Hedgehog.Tests.TryWithTryFinallyTests |
| 2 | + |
| 3 | +open Hedgehog |
| 4 | +open Hedgehog.FSharp |
| 5 | +open TestDsl |
| 6 | + |
| 7 | +// Simulate fluent assertion library for testing |
| 8 | +type AssertionResult = { Success: bool } |
| 9 | +let shouldBe expected actual = |
| 10 | + if actual = expected then { Success = true } |
| 11 | + else failwithf $"Expected %d{expected} but got %d{actual}" |
| 12 | + |
| 13 | +/// Tests for Property.tryFinally and Property.ignoreResult |
| 14 | +let tryWithTryFinallyTests = testList "Property.tryFinally and ignoreResult tests" [ |
| 15 | + |
| 16 | + testCase "tryFinally cleanup runs on success" <| fun () -> |
| 17 | + let mutable cleanupCalled = false |
| 18 | + property { |
| 19 | + let! x = Gen.constant 42 |
| 20 | + return x = 42 |
| 21 | + } |
| 22 | + |> Property.tryFinally (fun () -> cleanupCalled <- true) |
| 23 | + |> Property.checkBool |
| 24 | + |
| 25 | + Expect.isTrue cleanupCalled |
| 26 | + |
| 27 | + testCase "tryFinally cleanup runs on failure" <| fun () -> |
| 28 | + let mutable cleanupCalled = false |
| 29 | + let report = |
| 30 | + property { |
| 31 | + let! x = Gen.constant 42 |
| 32 | + return false |
| 33 | + } |
| 34 | + |> Property.tryFinally (fun () -> cleanupCalled <- true) |
| 35 | + |> Property.reportBool |
| 36 | + |
| 37 | + match report.Status with |
| 38 | + | Failed _ -> () |
| 39 | + | _ -> failwith "Expected Failed status" |
| 40 | + |
| 41 | + Expect.isTrue cleanupCalled |
| 42 | + |
| 43 | + testCase "ignoreResult converts Property<'a> to Property<unit>" <| fun () -> |
| 44 | + let mutable testRan = false |
| 45 | + property { |
| 46 | + let! x = Gen.constant 42 |
| 47 | + testRan <- true |
| 48 | + return shouldBe 42 x // Returns AssertionResult |
| 49 | + } |
| 50 | + |> Property.ignoreResult // Convert to Property<unit> |
| 51 | + |> Property.check |
| 52 | + |
| 53 | + |
| 54 | + testCase "ignoreResult preserves failures" <| fun () -> |
| 55 | + let report = |
| 56 | + property { |
| 57 | + let! x = Gen.constant 42 |
| 58 | + return shouldBe 99 x // Will throw |
| 59 | + } |
| 60 | + |> Property.ignoreResult |
| 61 | + |> Property.report |
| 62 | + |
| 63 | + match report.Status with |
| 64 | + | Failed _ -> () |
| 65 | + | _ -> failwith "Expected Failed status" |
| 66 | +] |
0 commit comments