Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 27 additions & 11 deletions TUnit.Assertions.FSharp/Extensions.fs
Original file line number Diff line number Diff line change
@@ -1,18 +1,34 @@
namespace TUnit.Assertions.FSharp

open TUnit.Assertions.AssertionBuilders
open TUnit.Assertions.AssertConditions.Throws

module Operations =
[<CustomOperation(MaintainsVariableSpaceUsingBind = true)>]
let check (assertion: IInvokableAssertionBuilder) =
let check (assertion: 'T) =
Async.FromContinuations(fun (cont, econt, ccont) ->
let awaiter = assertion.GetAwaiter()

awaiter.OnCompleted(fun () ->
try
if awaiter.IsCompleted then
cont(awaiter.GetResult())
else
ccont (System.OperationCanceledException())
with ex ->
econt ex))
match box assertion with
| :? IInvokableAssertionBuilder as invokable ->
let awaiter = invokable.GetAwaiter()
awaiter.OnCompleted(fun () ->
try
if awaiter.IsCompleted then
cont(awaiter.GetResult())
else
ccont (System.OperationCanceledException())
with ex ->
econt ex)
| :? ThrowsException<obj, exn> as throwsExn ->
let awaiter = throwsExn.GetAwaiter()
awaiter.OnCompleted(fun () ->
try
if awaiter.IsCompleted then
let _ = awaiter.GetResult() // ignore the exn result
cont ()
else
ccont (System.OperationCanceledException())
with ex ->
econt ex)
| _ ->
invalidOp $"Unsupported assertion type: We currently don't support Assertion Type {assertion.GetType()}"
)
28 changes: 27 additions & 1 deletion docs/docs/tutorial-assertions/fsharp.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,30 @@ member this.CheckPositive() = async {
let result = 1 + 1
do! check (Assert.That(result).IsPositive())
}
```
```

F# is a lot more strict with type resolution when it comes to extension methods and method overloads. Because of that you may need to annotate the type for the assertions.

For example,

```fsharp
[<Test>]
[<Category("Pass")>]
member _.Test3() = async {
let value = "1"
do! check (Assert.That<string>(value).IsEqualTo("1"))
}

[<Test>]
[<Category("Fail")>]
member _.Throws1() = async {
do! check (Assert.That<string>(fun () -> task { return new string([||]) }).ThrowsException())
}

[<Test>]
[<Category("Pass")>]
member _.Throws4() = async {
do! check (Assert.That<bool>(fun () -> Task.FromResult(true)).ThrowsNothing())
}

```
Loading