mirror of
https://github.com/Smaug123/unofficial-nunit-runner
synced 2025-10-06 01:48:38 +00:00
Compare commits
7 Commits
WoofWare.N
...
dependabot
Author | SHA1 | Date | |
---|---|---|---|
|
620d3fbebf | ||
|
12e3fc0e4f | ||
|
208b809096 | ||
|
b4e5baddcf | ||
|
5597b3f2f8 | ||
|
fcfdcef6cf | ||
|
eeada219f6 |
@@ -9,7 +9,7 @@
|
||||
]
|
||||
},
|
||||
"fsharp-analyzers": {
|
||||
"version": "0.32.0",
|
||||
"version": "0.32.1",
|
||||
"commands": [
|
||||
"fsharp-analyzers"
|
||||
]
|
||||
|
4
.github/workflows/dotnet.yaml
vendored
4
.github/workflows/dotnet.yaml
vendored
@@ -96,8 +96,8 @@ jobs:
|
||||
- name: Test using self
|
||||
run: 'nix develop --command dotnet exec ./WoofWare.NUnitTestRunner/bin/Release/net6.0/WoofWare.NUnitTestRunner.dll ./Consumer/bin/Release/net8.0/Consumer.dll --trx TrxOut/out.trx'
|
||||
- name: Parse Trx files
|
||||
uses: NasAmin/trx-parser@v0.6.0
|
||||
if: always()
|
||||
uses: NasAmin/trx-parser@v0.7.0
|
||||
if: always() && github.ref_name != 'main'
|
||||
id: trx-parser
|
||||
with:
|
||||
TRX_PATH: ${{ github.workspace }}/TrxOut
|
||||
|
@@ -10,6 +10,7 @@
|
||||
<Compile Include="NoAttribute.fs" />
|
||||
<Compile Include="Inconclusive.fs" />
|
||||
<Compile Include="RunSubProcess.fs" />
|
||||
<Compile Include="TestAsync.fs" />
|
||||
<Compile Include="TestExplicit.fs" />
|
||||
<Compile Include="TestNonParallel.fs" />
|
||||
<Compile Include="TestParallel.fs" />
|
||||
@@ -29,7 +30,7 @@
|
||||
<ItemGroup>
|
||||
<PackageReference Include="FsUnit" Version="7.1.1" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1"/>
|
||||
<PackageReference Include="NUnit" Version="4.3.2"/>
|
||||
<PackageReference Include="NUnit" Version="4.4.0"/>
|
||||
<PackageReference Include="NUnit3TestAdapter" Version="5.0.0"/>
|
||||
</ItemGroup>
|
||||
|
||||
|
23
Consumer/TestAsync.fs
Normal file
23
Consumer/TestAsync.fs
Normal file
@@ -0,0 +1,23 @@
|
||||
namespace Consumer
|
||||
|
||||
open System
|
||||
open System.Threading.Tasks
|
||||
open FsUnitTyped
|
||||
open NUnit.Framework
|
||||
|
||||
[<TestFixture>]
|
||||
module TestAsync =
|
||||
|
||||
[<Test>]
|
||||
let ``an async test`` () =
|
||||
async {
|
||||
do! Async.Sleep (TimeSpan.FromMilliseconds 20.0)
|
||||
1 |> shouldEqual 1
|
||||
}
|
||||
|
||||
[<Test>]
|
||||
let ``an async test, task-based`` () =
|
||||
task {
|
||||
do! Task.Delay (TimeSpan.FromMilliseconds 20.0)
|
||||
1 |> shouldEqual 1
|
||||
}
|
@@ -13,7 +13,7 @@
|
||||
<ItemGroup>
|
||||
<PackageReference Include="FsUnit" Version="7.1.1" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1"/>
|
||||
<PackageReference Include="NUnit" Version="4.3.2"/>
|
||||
<PackageReference Include="NUnit" Version="4.4.0"/>
|
||||
<PackageReference Include="NUnit3TestAdapter" Version="5.0.0"/>
|
||||
</ItemGroup>
|
||||
|
||||
|
@@ -4,16 +4,16 @@ open System
|
||||
open System.Threading
|
||||
open System.Threading.Tasks
|
||||
|
||||
type private ThunkEvaluator<'ret> =
|
||||
abstract Eval<'a> : (unit -> 'a) -> AsyncReplyChannel<Result<'a, exn>> -> 'ret
|
||||
type private AsyncThunkEvaluator<'ret> =
|
||||
abstract Eval<'a> : (unit -> Async<'a>) -> AsyncReplyChannel<Result<'a, exn>> -> 'ret
|
||||
|
||||
type private ThunkCrate =
|
||||
abstract Apply<'ret> : ThunkEvaluator<'ret> -> 'ret
|
||||
type private AsyncThunkCrate =
|
||||
abstract Apply<'ret> : AsyncThunkEvaluator<'ret> -> 'ret
|
||||
|
||||
[<RequireQualifiedAccess>]
|
||||
module private ThunkCrate =
|
||||
let make<'a> (t : unit -> 'a) (rc : AsyncReplyChannel<Result<'a, exn>>) : ThunkCrate =
|
||||
{ new ThunkCrate with
|
||||
module private AsyncThunkCrate =
|
||||
let make<'a> (t : unit -> Async<'a>) (rc : AsyncReplyChannel<Result<'a, exn>>) : AsyncThunkCrate =
|
||||
{ new AsyncThunkCrate with
|
||||
member _.Apply e = e.Eval t rc
|
||||
}
|
||||
|
||||
@@ -41,7 +41,11 @@ type private MailboxMessage =
|
||||
| Quit of AsyncReplyChannel<unit>
|
||||
/// Check current state, see if we need to start more tests, etc.
|
||||
| Reconcile
|
||||
| RunTest of within : TestFixture * Parallelizable<unit> option * test : ThunkCrate * context : ExecutionContext
|
||||
| RunTestAsync of
|
||||
within : TestFixture *
|
||||
Parallelizable<unit> option *
|
||||
test : AsyncThunkCrate *
|
||||
context : ExecutionContext
|
||||
| BeginTestFixture of TestFixture * AsyncReplyChannel<TestFixtureRunningToken>
|
||||
| EndTestFixture of TestFixtureTearDownToken * AsyncReplyChannel<unit>
|
||||
|
||||
@@ -310,26 +314,31 @@ type ParallelQueue
|
||||
rc.Reply ()
|
||||
m.Post MailboxMessage.Reconcile
|
||||
return! processTask (Running state) m
|
||||
| MailboxMessage.RunTest (withinFixture, par, message, capturedContext) ->
|
||||
| MailboxMessage.RunTestAsync (withinFixture, par, message, capturedContext) ->
|
||||
let t () =
|
||||
{ new ThunkEvaluator<_> with
|
||||
member _.Eval<'b> (t : unit -> 'b) rc =
|
||||
{ new AsyncThunkEvaluator<_> with
|
||||
member _.Eval<'b> (t : unit -> Async<'b>) rc =
|
||||
let tcs = TaskCompletionSource TaskCreationOptions.RunContinuationsAsynchronously
|
||||
|
||||
fun () ->
|
||||
ExecutionContext.Run (
|
||||
capturedContext,
|
||||
(fun _ ->
|
||||
let result =
|
||||
try
|
||||
let r = t ()
|
||||
Ok r
|
||||
with e ->
|
||||
Error e
|
||||
async {
|
||||
let! result =
|
||||
async {
|
||||
try
|
||||
let! r = t ()
|
||||
return Ok r
|
||||
with e ->
|
||||
return Error e
|
||||
}
|
||||
|
||||
tcs.SetResult ()
|
||||
m.Post MailboxMessage.Reconcile
|
||||
rc.Reply result
|
||||
tcs.SetResult ()
|
||||
m.Post MailboxMessage.Reconcile
|
||||
rc.Reply result
|
||||
}
|
||||
|> Async.StartImmediate
|
||||
),
|
||||
()
|
||||
)
|
||||
@@ -353,19 +362,19 @@ type ParallelQueue
|
||||
let mb = new MailboxProcessor<_> (processTask MailboxState.Idle)
|
||||
do mb.Start ()
|
||||
|
||||
/// Request to run the given action, freely in parallel with other running tests.
|
||||
/// Request to run the given async action, freely in parallel with other running tests.
|
||||
/// The resulting Task will return when the action has completed.
|
||||
member _.Run<'a>
|
||||
member _.RunAsync<'a>
|
||||
(TestFixtureSetupToken parent)
|
||||
(scope : Parallelizable<unit> option)
|
||||
(action : unit -> 'a)
|
||||
(action : unit -> Async<'a>)
|
||||
: 'a Task
|
||||
=
|
||||
let ec = ExecutionContext.Capture ()
|
||||
|
||||
task {
|
||||
let! result =
|
||||
(fun rc -> MailboxMessage.RunTest (parent, scope, ThunkCrate.make action rc, ec))
|
||||
(fun rc -> MailboxMessage.RunTestAsync (parent, scope, AsyncThunkCrate.make action rc, ec))
|
||||
|> mb.PostAndAsyncReply
|
||||
|> Async.StartAsTask
|
||||
|
||||
@@ -374,6 +383,16 @@ type ParallelQueue
|
||||
| Error e -> return Exception.reraiseWithOriginalStackTrace e
|
||||
}
|
||||
|
||||
/// Request to run the given action, freely in parallel with other running tests.
|
||||
/// The resulting Task will return when the action has completed.
|
||||
member this.Run<'a>
|
||||
(parent : TestFixtureSetupToken)
|
||||
(scope : Parallelizable<unit> option)
|
||||
(action : unit -> 'a)
|
||||
: 'a Task
|
||||
=
|
||||
this.RunAsync parent scope (fun () -> async.Return (action ()))
|
||||
|
||||
/// Declare that we wish to start the given test fixture. The resulting Task will return
|
||||
/// when you are allowed to start running tests from that fixture.
|
||||
/// Once you've finished running tests from that fixture, call EndTestFixture.
|
||||
@@ -396,7 +415,14 @@ type ParallelQueue
|
||||
let ec = ExecutionContext.Capture ()
|
||||
|
||||
let! response =
|
||||
(fun rc -> MailboxMessage.RunTest (parent, par, ThunkCrate.make action rc, ec))
|
||||
(fun rc ->
|
||||
MailboxMessage.RunTestAsync (
|
||||
parent,
|
||||
par,
|
||||
AsyncThunkCrate.make (fun () -> async.Return (action ())) rc,
|
||||
ec
|
||||
)
|
||||
)
|
||||
|> mb.PostAndAsyncReply
|
||||
|
||||
match response with
|
||||
@@ -422,7 +448,14 @@ type ParallelQueue
|
||||
let ec = ExecutionContext.Capture ()
|
||||
|
||||
let! response =
|
||||
(fun rc -> MailboxMessage.RunTest (parent, par, ThunkCrate.make action rc, ec))
|
||||
(fun rc ->
|
||||
MailboxMessage.RunTestAsync (
|
||||
parent,
|
||||
par,
|
||||
AsyncThunkCrate.make (fun () -> async.Return (action ())) rc,
|
||||
ec
|
||||
)
|
||||
)
|
||||
|> mb.PostAndAsyncReply
|
||||
|
||||
match response with
|
||||
|
@@ -256,6 +256,7 @@ WoofWare.NUnitTestRunner.ParallelQueue inherit obj, implements IDisposable
|
||||
WoofWare.NUnitTestRunner.ParallelQueue..ctor [constructor]: (int option, WoofWare.NUnitTestRunner.AssemblyParallelScope WoofWare.NUnitTestRunner.Parallelizable option, System.Threading.CancellationToken option)
|
||||
WoofWare.NUnitTestRunner.ParallelQueue.EndTestFixture [method]: WoofWare.NUnitTestRunner.TestFixtureTearDownToken -> unit System.Threading.Tasks.Task
|
||||
WoofWare.NUnitTestRunner.ParallelQueue.Run [method]: WoofWare.NUnitTestRunner.TestFixtureSetupToken -> unit WoofWare.NUnitTestRunner.Parallelizable option -> (unit -> 'a) -> 'a System.Threading.Tasks.Task
|
||||
WoofWare.NUnitTestRunner.ParallelQueue.RunAsync [method]: WoofWare.NUnitTestRunner.TestFixtureSetupToken -> unit WoofWare.NUnitTestRunner.Parallelizable option -> (unit -> 'a Microsoft.FSharp.Control.FSharpAsync) -> 'a System.Threading.Tasks.Task
|
||||
WoofWare.NUnitTestRunner.ParallelQueue.RunTestSetup [method]: WoofWare.NUnitTestRunner.TestFixtureRunningToken -> (unit -> 'a) -> ('a * WoofWare.NUnitTestRunner.TestFixtureSetupToken) System.Threading.Tasks.Task
|
||||
WoofWare.NUnitTestRunner.ParallelQueue.RunTestTearDown [method]: WoofWare.NUnitTestRunner.TestFixtureSetupToken -> (unit -> 'a) -> ('a * WoofWare.NUnitTestRunner.TestFixtureTearDownToken) System.Threading.Tasks.Task
|
||||
WoofWare.NUnitTestRunner.ParallelQueue.StartTestFixture [method]: WoofWare.NUnitTestRunner.TestFixture -> WoofWare.NUnitTestRunner.TestFixtureRunningToken System.Threading.Tasks.Task
|
||||
|
@@ -76,105 +76,168 @@ module TestFixture =
|
||||
(test : MethodInfo)
|
||||
(containingObject : obj)
|
||||
(args : obj[])
|
||||
: Result<TestMemberSuccess, TestFailure list> * IndividualTestRunMetadata
|
||||
: Async<Result<TestMemberSuccess, TestFailure list> * IndividualTestRunMetadata>
|
||||
=
|
||||
let rec runMethods
|
||||
(wrap : UserMethodFailure -> TestFailure)
|
||||
(toRun : MethodInfo list)
|
||||
(args : obj[])
|
||||
: Result<unit, _>
|
||||
: Result<unit, TestFailure> Async
|
||||
=
|
||||
match toRun with
|
||||
| [] -> Ok ()
|
||||
| [] -> async.Return (Ok ())
|
||||
| head :: rest ->
|
||||
let result =
|
||||
try
|
||||
head.Invoke (containingObject, args) |> Ok
|
||||
with
|
||||
| :? TargetInvocationException as e -> Error (UserMethodFailure.Threw (head.Name, e.InnerException))
|
||||
| :? TargetParameterCountException ->
|
||||
UserMethodFailure.BadParameters (
|
||||
head.Name,
|
||||
head.GetParameters () |> Array.map (fun pm -> pm.ParameterType),
|
||||
args
|
||||
)
|
||||
|> Error
|
||||
async {
|
||||
let result =
|
||||
try
|
||||
head.Invoke (containingObject, args) |> Ok
|
||||
with
|
||||
| :? TargetInvocationException as e ->
|
||||
Error (UserMethodFailure.Threw (head.Name, e.InnerException))
|
||||
| :? TargetParameterCountException ->
|
||||
UserMethodFailure.BadParameters (
|
||||
head.Name,
|
||||
head.GetParameters () |> Array.map (fun pm -> pm.ParameterType),
|
||||
args
|
||||
)
|
||||
|> Error
|
||||
|
||||
match result with
|
||||
| Error e -> Error (wrap e)
|
||||
| Ok result ->
|
||||
match result with
|
||||
| :? unit -> runMethods wrap rest args
|
||||
| ret -> UserMethodFailure.ReturnedNonUnit (head.Name, ret) |> wrap |> Error
|
||||
let! ct = Async.CancellationToken
|
||||
|
||||
let start = DateTimeOffset.Now
|
||||
let! result =
|
||||
match result with
|
||||
| Error e -> async.Return (Error (wrap e))
|
||||
| Ok result ->
|
||||
match result with
|
||||
| :? unit -> runMethods wrap rest args
|
||||
| :? Task as result ->
|
||||
async {
|
||||
let mutable exc = None
|
||||
|
||||
let sw = Stopwatch.StartNew ()
|
||||
try
|
||||
do! Async.AwaitTask result
|
||||
with e ->
|
||||
exc <- Some e
|
||||
|
||||
let metadata () =
|
||||
let name =
|
||||
if args.Length = 0 then
|
||||
test.Name
|
||||
else
|
||||
let argsStr = args |> Seq.map string<obj> |> String.concat ","
|
||||
$"%s{test.Name}(%s{argsStr})"
|
||||
match exc with
|
||||
| None -> return! runMethods wrap rest args
|
||||
| Some e -> return Error (UserMethodFailure.Threw (head.Name, e) |> wrap)
|
||||
}
|
||||
// We'd like to do this type-test:
|
||||
// | :? Async<unit> as result ->
|
||||
// but instead we have to do all this reflective nonsense, because FSharpAsync is not part
|
||||
// of the .NET runtime, so is instead in a different AssemblyLoadContext to us!
|
||||
// It's in the user-code context, not ours.
|
||||
| ret ->
|
||||
let ty = ret.GetType ()
|
||||
|
||||
{
|
||||
End = DateTimeOffset.Now
|
||||
Start = start
|
||||
Total = sw.Elapsed
|
||||
ComputerName = Environment.MachineName
|
||||
ExecutionId = Guid.NewGuid ()
|
||||
TestId = testId
|
||||
TestName = name
|
||||
ClassName = test.DeclaringType.FullName
|
||||
StdOut =
|
||||
match contexts.DumpStdout outputId with
|
||||
| "" -> None
|
||||
| v -> Some v
|
||||
StdErr =
|
||||
match contexts.DumpStderr outputId with
|
||||
| "" -> None
|
||||
| v -> Some v
|
||||
}
|
||||
if ty.Namespace = "Microsoft.FSharp.Control" && ty.Name = "FSharpAsync`1" then
|
||||
match ty.GenericTypeArguments |> Array.map (fun t -> t.FullName) with
|
||||
| [| "Microsoft.FSharp.Core.Unit" |] ->
|
||||
let asyncModule = ty.Assembly.GetType ("Microsoft.FSharp.Control.FSharpAsync")
|
||||
// let catch = asyncModule.GetMethod("Catch").MakeGenericMethod [| ty.GenericTypeArguments.[0] |]
|
||||
// let caught = catch.Invoke ((null: obj), [| ret |])
|
||||
let startAsTask =
|
||||
asyncModule.GetMethod("StartAsTask").MakeGenericMethod
|
||||
[| ty.GenericTypeArguments.[0] |]
|
||||
|
||||
let setUpResult = runMethods TestFailure.SetUpFailed setUp [||]
|
||||
sw.Stop ()
|
||||
let started =
|
||||
startAsTask.Invoke ((null : obj), [| ret ; (null : obj) ; (null : obj) |])
|
||||
|> unbox<Task>
|
||||
|
||||
match setUpResult with
|
||||
| Error e -> Error [ e ], metadata ()
|
||||
| Ok () ->
|
||||
async {
|
||||
let! res = Async.AwaitTask started |> Async.Catch
|
||||
|
||||
sw.Start ()
|
||||
match res with
|
||||
| Choice1Of2 () -> return! runMethods wrap rest args
|
||||
| Choice2Of2 e ->
|
||||
return
|
||||
Error (
|
||||
UserMethodFailure.Threw (head.Name, started.Exception) |> wrap
|
||||
)
|
||||
}
|
||||
| _ ->
|
||||
UserMethodFailure.ReturnedNonUnit (head.Name, ret)
|
||||
|> wrap
|
||||
|> Error
|
||||
|> async.Return
|
||||
else
|
||||
async.Return (UserMethodFailure.ReturnedNonUnit (head.Name, ret) |> wrap |> Error)
|
||||
|
||||
let result =
|
||||
let result = runMethods TestFailure.TestFailed [ test ] args
|
||||
return result
|
||||
}
|
||||
|
||||
async {
|
||||
let start = DateTimeOffset.Now
|
||||
|
||||
let sw = Stopwatch.StartNew ()
|
||||
|
||||
let metadata () =
|
||||
let name =
|
||||
if args.Length = 0 then
|
||||
test.Name
|
||||
else
|
||||
let argsStr = args |> Seq.map string<obj> |> String.concat ","
|
||||
$"%s{test.Name}(%s{argsStr})"
|
||||
|
||||
{
|
||||
End = DateTimeOffset.Now
|
||||
Start = start
|
||||
Total = sw.Elapsed
|
||||
ComputerName = Environment.MachineName
|
||||
ExecutionId = Guid.NewGuid ()
|
||||
TestId = testId
|
||||
TestName = name
|
||||
ClassName = test.DeclaringType.FullName
|
||||
StdOut =
|
||||
match contexts.DumpStdout outputId with
|
||||
| "" -> None
|
||||
| v -> Some v
|
||||
StdErr =
|
||||
match contexts.DumpStderr outputId with
|
||||
| "" -> None
|
||||
| v -> Some v
|
||||
}
|
||||
|
||||
let! setUpResult = runMethods TestFailure.SetUpFailed setUp [||]
|
||||
sw.Stop ()
|
||||
|
||||
match result with
|
||||
| Ok () -> Ok None
|
||||
| Error (TestFailure.TestFailed (UserMethodFailure.Threw (_, exc)) as orig) ->
|
||||
match exc.GetType().FullName with
|
||||
| "NUnit.Framework.SuccessException" -> Ok None
|
||||
| "NUnit.Framework.IgnoreException" -> Ok (Some (TestMemberSuccess.Ignored (Option.ofObj exc.Message)))
|
||||
| "NUnit.Framework.InconclusiveException" ->
|
||||
Ok (Some (TestMemberSuccess.Inconclusive (Option.ofObj exc.Message)))
|
||||
| _ -> Error orig
|
||||
| Error orig -> Error orig
|
||||
match setUpResult with
|
||||
| Error e -> return Error [ e ], metadata ()
|
||||
| Ok () ->
|
||||
|
||||
// Unconditionally run TearDown after tests, even if tests failed.
|
||||
sw.Start ()
|
||||
let tearDownResult = runMethods TestFailure.TearDownFailed tearDown [||]
|
||||
sw.Stop ()
|
||||
sw.Start ()
|
||||
let! result = runMethods TestFailure.TestFailed [ test ] args
|
||||
sw.Stop ()
|
||||
|
||||
let metadata = metadata ()
|
||||
let result =
|
||||
match result with
|
||||
| Ok () -> Ok None
|
||||
| Error (TestFailure.TestFailed (UserMethodFailure.Threw (_, exc)) as orig) ->
|
||||
match exc.GetType().FullName with
|
||||
| "NUnit.Framework.SuccessException" -> Ok None
|
||||
| "NUnit.Framework.IgnoreException" ->
|
||||
Ok (Some (TestMemberSuccess.Ignored (Option.ofObj exc.Message)))
|
||||
| "NUnit.Framework.InconclusiveException" ->
|
||||
Ok (Some (TestMemberSuccess.Inconclusive (Option.ofObj exc.Message)))
|
||||
| _ -> Error orig
|
||||
| Error orig -> Error orig
|
||||
|
||||
match result, tearDownResult with
|
||||
| Ok None, Ok () -> Ok TestMemberSuccess.Ok, metadata
|
||||
| Ok (Some s), Ok () -> Ok s, metadata
|
||||
| Error e, Ok ()
|
||||
| Ok _, Error e -> Error [ e ], metadata
|
||||
| Error e1, Error e2 -> Error [ e1 ; e2 ], metadata
|
||||
// Unconditionally run TearDown after tests, even if tests failed.
|
||||
sw.Start ()
|
||||
let! tearDownResult = runMethods TestFailure.TearDownFailed tearDown [||]
|
||||
sw.Stop ()
|
||||
|
||||
let metadata = metadata ()
|
||||
|
||||
return
|
||||
match result, tearDownResult with
|
||||
| Ok None, Ok () -> Ok TestMemberSuccess.Ok, metadata
|
||||
| Ok (Some s), Ok () -> Ok s, metadata
|
||||
| Error e, Ok ()
|
||||
| Ok _, Error e -> Error [ e ], metadata
|
||||
| Error e1, Error e2 -> Error [ e1 ; e2 ], metadata
|
||||
}
|
||||
|
||||
let private getValues (test : SingleTestMethod) =
|
||||
let valuesAttrs =
|
||||
@@ -395,20 +458,22 @@ module TestFixture =
|
||||
|> Seq.map (fun (testGuid, args) ->
|
||||
task {
|
||||
let runMe () =
|
||||
progress.OnTestMemberStart test.Name
|
||||
let oldValue = contexts.AsyncLocal.Value
|
||||
let outputId = contexts.NewOutputs ()
|
||||
contexts.AsyncLocal.Value <- outputId
|
||||
async {
|
||||
progress.OnTestMemberStart test.Name
|
||||
let oldValue = contexts.AsyncLocal.Value
|
||||
let outputId = contexts.NewOutputs ()
|
||||
contexts.AsyncLocal.Value <- outputId
|
||||
|
||||
let result, meta =
|
||||
runOne outputId contexts setUp tearDown testGuid test.Method containingObject args
|
||||
let! result, meta =
|
||||
runOne outputId contexts setUp tearDown testGuid test.Method containingObject args
|
||||
|
||||
contexts.AsyncLocal.Value <- oldValue
|
||||
progress.OnTestMemberFinished test.Name
|
||||
contexts.AsyncLocal.Value <- oldValue
|
||||
progress.OnTestMemberFinished test.Name
|
||||
|
||||
result, meta
|
||||
return result, meta
|
||||
}
|
||||
|
||||
let! results, summary = par.Run running test.Parallelize runMe
|
||||
let! results, summary = par.RunAsync running test.Parallelize runMe
|
||||
|
||||
match results with
|
||||
| Ok results -> return Ok results, summary
|
||||
|
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"version": "0.21",
|
||||
"version": "0.22",
|
||||
"publicReleaseRefSpec": [
|
||||
"^refs/heads/main$"
|
||||
],
|
||||
@@ -8,4 +8,4 @@
|
||||
":/Directory.Build.props",
|
||||
":/README.md"
|
||||
]
|
||||
}
|
||||
}
|
@@ -243,23 +243,18 @@ module TestSynchronizationContext =
|
||||
do! queue.EndTestFixture teardown
|
||||
}
|
||||
|
||||
(*
|
||||
[<Test>]
|
||||
let ``ExecutionContext flows correctly through async operations`` () =
|
||||
task {
|
||||
// Create a test fixture
|
||||
let dummyFixture =
|
||||
TestFixture.Empty
|
||||
typeof<obj>
|
||||
(Some (Parallelizable.Yes ClassParallelScope.All))
|
||||
[]
|
||||
[]
|
||||
TestFixture.Empty typeof<obj> (Some (Parallelizable.Yes ClassParallelScope.All)) [] []
|
||||
|
||||
use contexts = TestContexts.Empty ()
|
||||
use queue = new ParallelQueue(Some 4, None)
|
||||
use queue = new ParallelQueue (Some 4, None)
|
||||
|
||||
// Track which context values we see during execution
|
||||
let contextValues = System.Collections.Concurrent.ConcurrentBag<Guid * Guid>()
|
||||
let contextValues = System.Collections.Concurrent.ConcurrentBag<Guid * Guid> ()
|
||||
|
||||
// Start the fixture
|
||||
let! running = queue.StartTestFixture dummyFixture
|
||||
@@ -267,42 +262,45 @@ module TestSynchronizationContext =
|
||||
|
||||
// Create several async operations with different context values
|
||||
let tasks =
|
||||
[1..10]
|
||||
[ 1..10 ]
|
||||
|> List.map (fun i ->
|
||||
task {
|
||||
// Set a unique context value
|
||||
let expectedId = Guid.NewGuid()
|
||||
let expectedId = Guid.NewGuid ()
|
||||
let outputId = OutputStreamId expectedId
|
||||
contexts.AsyncLocal.Value <- outputId
|
||||
|
||||
// Run an async operation that checks the context at multiple points
|
||||
let! actualId =
|
||||
queue.RunAsync setup None (fun () ->
|
||||
async {
|
||||
// Check context immediately
|
||||
let immediate = contexts.AsyncLocal.Value
|
||||
let (OutputStreamId immediateGuid) = immediate
|
||||
contextValues.Add(expectedId, immediateGuid)
|
||||
queue.RunAsync
|
||||
setup
|
||||
None
|
||||
(fun () ->
|
||||
async {
|
||||
// Check context immediately
|
||||
let immediate = contexts.AsyncLocal.Value
|
||||
let (OutputStreamId immediateGuid) = immediate
|
||||
contextValues.Add (expectedId, immediateGuid)
|
||||
|
||||
// Yield to allow potential context loss
|
||||
do! Async.Sleep 10
|
||||
// Yield to allow potential context loss
|
||||
do! Async.Sleep 10
|
||||
|
||||
// Check context after yield
|
||||
let afterYield = contexts.AsyncLocal.Value
|
||||
let (OutputStreamId afterYieldGuid) = afterYield
|
||||
contextValues.Add(expectedId, afterYieldGuid)
|
||||
// Check context after yield
|
||||
let afterYield = contexts.AsyncLocal.Value
|
||||
let (OutputStreamId afterYieldGuid) = afterYield
|
||||
contextValues.Add (expectedId, afterYieldGuid)
|
||||
|
||||
// Do some actual async work
|
||||
do! Task.Delay(10) |> Async.AwaitTask
|
||||
// Do some actual async work
|
||||
do! Task.Delay (10) |> Async.AwaitTask
|
||||
|
||||
// Check context after task
|
||||
let afterTask = contexts.AsyncLocal.Value
|
||||
let (OutputStreamId afterTaskGuid) = afterTask
|
||||
contextValues.Add(expectedId, afterTaskGuid)
|
||||
// Check context after task
|
||||
let afterTask = contexts.AsyncLocal.Value
|
||||
let (OutputStreamId afterTaskGuid) = afterTask
|
||||
contextValues.Add (expectedId, afterTaskGuid)
|
||||
|
||||
return afterTaskGuid
|
||||
}
|
||||
)
|
||||
return afterTaskGuid
|
||||
}
|
||||
)
|
||||
|
||||
// Verify the returned value matches what we set
|
||||
actualId |> shouldEqual expectedId
|
||||
@@ -310,16 +308,16 @@ module TestSynchronizationContext =
|
||||
)
|
||||
|
||||
// Wait for all tasks
|
||||
let! results = Task.WhenAll(tasks)
|
||||
let! results = Task.WhenAll (tasks)
|
||||
results |> Array.iter id
|
||||
|
||||
// Verify all context values were correct
|
||||
let allValues = contextValues |> Seq.toList
|
||||
allValues |> shouldHaveLength 30 // 3 checks per operation * 10 operations
|
||||
allValues |> shouldHaveLength 30 // 3 checks per operation * 10 operations
|
||||
|
||||
// Every captured value should match its expected value
|
||||
for expected, actual in allValues do
|
||||
actual |> shouldEqual expected
|
||||
allValues
|
||||
|> List.iter (fun (expected, actual) -> actual |> shouldEqual expected)
|
||||
|
||||
// Clean up
|
||||
let! _, teardown = queue.RunTestTearDown setup (fun () -> ())
|
||||
@@ -330,80 +328,69 @@ module TestSynchronizationContext =
|
||||
let ``ExecutionContext isolation between concurrent operations`` () =
|
||||
task {
|
||||
let dummyFixture =
|
||||
TestFixture.Empty
|
||||
typeof<obj>
|
||||
(Some (Parallelizable.Yes ClassParallelScope.All))
|
||||
[]
|
||||
[]
|
||||
TestFixture.Empty typeof<obj> (Some (Parallelizable.Yes ClassParallelScope.All)) [] []
|
||||
|
||||
use contexts = TestContexts.Empty ()
|
||||
use queue = new ParallelQueue(Some 4, None)
|
||||
use queue = new ParallelQueue (Some 4, None)
|
||||
|
||||
let! running = queue.StartTestFixture dummyFixture
|
||||
let! _, setup = queue.RunTestSetup running (fun () -> ())
|
||||
|
||||
// Use a barrier to ensure operations run concurrently
|
||||
let barrier = new Barrier(3)
|
||||
let seenValues = System.Collections.Concurrent.ConcurrentBag<int * Guid option>()
|
||||
let barrier = new Barrier (3)
|
||||
let seenValues = System.Collections.Concurrent.ConcurrentBag<int * Guid> ()
|
||||
|
||||
// Create operations that will definitely run concurrently
|
||||
let tasks =
|
||||
[1..3]
|
||||
[ 1..3 ]
|
||||
|> List.map (fun i ->
|
||||
task {
|
||||
// Each task sets its own context value
|
||||
let myId = Guid.NewGuid()
|
||||
let myId = Guid.NewGuid ()
|
||||
contexts.AsyncLocal.Value <- OutputStreamId myId
|
||||
|
||||
let! result =
|
||||
queue.RunAsync setup (Some (Parallelizable.Yes ())) (fun () ->
|
||||
async {
|
||||
// Wait for all tasks to reach this point
|
||||
barrier.SignalAndWait() |> ignore
|
||||
queue.RunAsync
|
||||
setup
|
||||
(Some (Parallelizable.Yes ()))
|
||||
(fun () ->
|
||||
async {
|
||||
// Wait for all tasks to reach this point
|
||||
barrier.SignalAndWait () |> ignore
|
||||
|
||||
// Now check what value we see
|
||||
let currentValue = contexts.AsyncLocal.Value
|
||||
match currentValue with
|
||||
| OutputStreamId guid -> seenValues.Add(i, Some guid)
|
||||
| _ -> seenValues.Add(i, None)
|
||||
// Now check what value we see
|
||||
let currentValue = contexts.AsyncLocal.Value
|
||||
|
||||
// Do some async work
|
||||
do! Async.Sleep 5
|
||||
match currentValue with
|
||||
| OutputStreamId guid -> seenValues.Add (i, guid)
|
||||
|
||||
// Check again after async work
|
||||
let afterAsync = contexts.AsyncLocal.Value
|
||||
match afterAsync with
|
||||
| OutputStreamId guid ->
|
||||
return guid
|
||||
| _ ->
|
||||
return failwith "Lost context after async"
|
||||
}
|
||||
)
|
||||
// Do some async work
|
||||
do! Async.Sleep 5
|
||||
|
||||
// Check again after async work
|
||||
let afterAsync = contexts.AsyncLocal.Value
|
||||
|
||||
match afterAsync with
|
||||
| OutputStreamId guid -> return guid
|
||||
}
|
||||
)
|
||||
|
||||
// Each task should see its own value
|
||||
result |> shouldEqual myId
|
||||
}
|
||||
)
|
||||
|
||||
let! results = Task.WhenAll(tasks)
|
||||
let! results = Task.WhenAll (tasks)
|
||||
results |> Array.iter id
|
||||
|
||||
// Verify we saw 3 different values (one per task)
|
||||
let values = seenValues |> Seq.toList
|
||||
values |> shouldHaveLength 3
|
||||
|
||||
// Each task should have seen a value
|
||||
for (taskId, value) in values do
|
||||
value |> shouldNotEqual None
|
||||
|
||||
// All seen values should be different (no context bleeding)
|
||||
let uniqueValues =
|
||||
values
|
||||
|> List.choose snd
|
||||
|> List.distinct
|
||||
let uniqueValues = values |> List.map snd |> List.distinct
|
||||
uniqueValues |> shouldHaveLength 3
|
||||
|
||||
let! _, teardown = queue.RunTestTearDown setup (fun () -> ())
|
||||
do! queue.EndTestFixture teardown
|
||||
}
|
||||
*)
|
||||
|
@@ -21,7 +21,7 @@
|
||||
<PackageReference Include="FsCheck" Version="3.3.0" />
|
||||
<PackageReference Include="FsUnit" Version="7.1.1" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
|
||||
<PackageReference Include="NUnit" Version="4.3.2" />
|
||||
<PackageReference Include="NUnit" Version="4.4.0" />
|
||||
<PackageReference Include="NUnit3TestAdapter" Version="5.0.0"/>
|
||||
</ItemGroup>
|
||||
|
||||
|
6
flake.lock
generated
6
flake.lock
generated
@@ -20,11 +20,11 @@
|
||||
},
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1753432016,
|
||||
"narHash": "sha256-cnL5WWn/xkZoyH/03NNUS7QgW5vI7D1i74g48qplCvg=",
|
||||
"lastModified": 1754711617,
|
||||
"narHash": "sha256-WrZ280bT6NzNbBo+CKeJA/NW1rhvN/RUPZczqCpu2mI=",
|
||||
"owner": "NixOS",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "6027c30c8e9810896b92429f0092f624f7b1aace",
|
||||
"rev": "00b574b1ba8a352f0601c4dde4faff4b534ebb1e",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
|
@@ -26,8 +26,8 @@
|
||||
},
|
||||
{
|
||||
"pname": "fsharp-analyzers",
|
||||
"version": "0.32.0",
|
||||
"hash": "sha256-MnhsK5tOeexL6uQhsV4nTRz8CGbz2o8VyHwAK8x91pE="
|
||||
"version": "0.32.1",
|
||||
"hash": "sha256-le6rPnAF7cKGBZ2w8H2u9glK+6rT2ZjiAVnrkH2IhrM="
|
||||
},
|
||||
{
|
||||
"pname": "FSharp.Core",
|
||||
|
Reference in New Issue
Block a user