nunit
nunit copied to clipboard
SynchronizationContext not preserved from OneTimeSetup to Test method.
A test similar to the code below worked in 3.12, but not in 3.13. It actually works on net5.0 but not on net48.
[TestFixture]
internal sealed class LostSynchronizationContext
{
private SynchronizationContext m_OriginalSynchronizationContext;
private TestSynchronizationContext m_TestSynchronizationContext;
[OneTimeSetUp]
public void SetContext()
{
m_TestSynchronizationContext = new TestSynchronizationContext();
m_OriginalSynchronizationContext = SynchronizationContext.Current;
SynchronizationContext.SetSynchronizationContext(m_TestSynchronizationContext);
}
[OneTimeTearDown]
public void ResetContext()
{
SynchronizationContext.SetSynchronizationContext(m_OriginalSynchronizationContext);
}
[SetUp]
public void Setup()
{
Assert.That(SynchronizationContext.Current, Is.SameAs(m_TestSynchronizationContext));
}
[Test]
public void VerifySynchronized()
{
Assert.That(SynchronizationContext.Current, Is.SameAs(m_TestSynchronizationContext));
}
public class TestSynchronizationContext : SynchronizationContext
{
}
}
The code in ContextUtils captures the current ExecutionContext
and then runs it on that same context. @jnm2 Can you explain what that does or do you only actually need the restore part in case a test modifies it and you could call callback(state)
directly?
The problem on .NET Framework is that the synchronization context is not preserved: ExecutionContext
Even though the code can, it passes in false
to the preserveSyncCtx parameter.
Another option to restore behaviour for .net48 would be to explicitly set the SynchronizationContext
in the method passed to ExecutionContext.Run
.
I think we should try to make this work. It could be a tricky call-nesting problem in NUnit's execution. It might make sense to do this together with https://github.com/nunit/nunit/issues/4012#issuecomment-983106320.
@jnm2 I don't have much experience in this part of the framework, but I may have some pockets of time over the next 2 months to investigate this. Are there any tips or "gotchas" you could advise on for if I put someone else work on this
@manfred-brands @stevenaw Can we get something done here, or should it be moved off the milestone for 3.14 ? From what I can see on #4012 it might be difficult to handle this without major investigations and fixes.
I agree with @jnm2 that this would be good to get done but I don't think I'll have time to tackle this myself in the near future so I'm fine with deferring it. I'm curious if it could be tricky to get right if combined with the recently added "instance per parallel test" feature. I'll remove it now, but if someone feels strongly they can add it back to the milestone