Imported Upstream version 3.6.0

Former-commit-id: da6be194a6b1221998fc28233f2503bd61dd9d14
This commit is contained in:
Jo Shields
2014-08-13 10:39:27 +01:00
commit a575963da9
50588 changed files with 8155799 additions and 0 deletions

View File

@@ -0,0 +1,120 @@
//
// AutoResetEventTest.cs - NUnit test cases for System.Threading.AutoResetEvent
//
// Author:
// Gonzalo Paniagua Javier (gonzalo@ximian.com)
// Gert Driesen <gert.driesen@telenet.be>
//
// Copyright 2005 Novell, Inc (http://www.novell.com)
// Copyright 2007 Gert Driesen
//
using NUnit.Framework;
using System;
using System.Threading;
#if NET_2_0
using Microsoft.Win32.SafeHandles;
#endif
namespace MonoTests.System.Threading
{
[TestFixture]
public class AutoResetEventTest
{
[Test]
public void MultipleSet ()
{
AutoResetEvent evt = new AutoResetEvent (true);
Assert.IsTrue (evt.WaitOne (1000, false), "#1");
evt.Set ();
evt.Set ();
Assert.IsTrue (evt.WaitOne (1000, false), "#2");
Assert.IsFalse (evt.WaitOne (1000, false), "#3");
}
#if NET_2_0
[Test] // bug #81529
public void SafeWaitHandle ()
{
AutoResetEvent are1 = new AutoResetEvent (false);
AutoResetEvent are2 = new AutoResetEvent (false);
SafeWaitHandle swh1 = are1.SafeWaitHandle;
SafeWaitHandle swh2 = are2.SafeWaitHandle;
are1.SafeWaitHandle = are2.SafeWaitHandle;
Assert.AreSame (are1.SafeWaitHandle, are2.SafeWaitHandle, "#1");
Assert.AreEqual (are1.Handle, are2.Handle, "#2");
Assert.IsFalse (are1.SafeWaitHandle.IsInvalid, "#3");
Assert.IsFalse (are1.SafeWaitHandle.IsClosed, "#4");
Assert.IsFalse (swh1.IsClosed, "#5");
Assert.IsFalse (swh1.IsInvalid, "#6");
swh1.Dispose ();
are1.Close ();
}
[Test] // bug #81529
public void SafeWaitHandle_Null ()
{
AutoResetEvent are1 = new AutoResetEvent (false);
SafeWaitHandle swh1 = are1.SafeWaitHandle;
are1.SafeWaitHandle = null;
Assert.IsNotNull (are1.SafeWaitHandle, "#1");
Assert.AreEqual (-1, (int) are1.Handle, "#2");
Assert.IsTrue (are1.SafeWaitHandle.IsInvalid, "#3");
Assert.IsFalse (are1.SafeWaitHandle.IsClosed, "#4");
Assert.IsFalse (swh1.IsClosed, "#5");
Assert.IsFalse (swh1.IsInvalid, "#6");
}
[Test] // bug #81529
// Causes a Attempting to unref unused handle 0x2 warning
[Category ("NotWorking")]
public void Handle_Valid ()
{
AutoResetEvent are1 = new AutoResetEvent (false);
SafeWaitHandle swh1 = are1.SafeWaitHandle;
Assert.IsFalse (swh1.IsClosed, "#1");
Assert.IsFalse (swh1.IsInvalid, "#2");
IntPtr dummyHandle = (IntPtr) 2;
are1.Handle = dummyHandle;
Assert.AreEqual (are1.Handle, dummyHandle, "#3");
Assert.IsFalse (swh1.IsClosed, "#4");
Assert.IsFalse (swh1.IsClosed, "#5");
Assert.IsFalse (swh1.IsInvalid, "#6");
Assert.IsFalse (are1.SafeWaitHandle.IsClosed, "#7");
Assert.IsFalse (are1.SafeWaitHandle.IsInvalid, "#8");
are1.Close ();
swh1.Dispose ();
}
[Test] // bug #81529
public void Handle_Invalid ()
{
AutoResetEvent are1 = new AutoResetEvent (false);
SafeWaitHandle swh1 = are1.SafeWaitHandle;
are1.Handle = (IntPtr) (-1);
Assert.IsTrue (swh1 != are1.SafeWaitHandle, "#1");
Assert.IsFalse (swh1.IsClosed, "#2");
Assert.IsFalse (swh1.IsInvalid, "#3");
Assert.IsFalse (are1.SafeWaitHandle.IsClosed, "#4");
Assert.IsTrue (are1.SafeWaitHandle.IsInvalid, "#5");
are1.Close ();
swh1.Dispose ();
}
[Test] // bug #81529
public void Handle_ZeroPtr ()
{
AutoResetEvent are1 = new AutoResetEvent (false);
SafeWaitHandle swh1 = are1.SafeWaitHandle;
are1.Handle = IntPtr.Zero;
Assert.IsTrue (swh1 != are1.SafeWaitHandle, "#1");
Assert.IsFalse (swh1.IsClosed, "#2");
Assert.IsFalse (swh1.IsInvalid, "#3");
Assert.IsFalse (are1.SafeWaitHandle.IsClosed, "#4");
Assert.IsTrue (are1.SafeWaitHandle.IsInvalid, "#5");
are1.Close ();
swh1.Dispose ();
}
#endif
}
}

View File

@@ -0,0 +1,494 @@
//
// CancellationTokenSourceTest.cs
//
// Authors:
// Marek Safar (marek.safar@gmail.com)
// Jeremie Laval (jeremie.laval@gmail.com)
//
// Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#if NET_4_0
using System;
using System.Threading;
using NUnit.Framework;
using System.Threading.Tasks;
using MonoTests.System.Threading.Tasks;
namespace MonoTests.System.Threading
{
[TestFixture]
public class CancellationTokenSourceTest
{
#if NET_4_5
[Test]
public void Ctor_Invalid ()
{
try {
new CancellationTokenSource (-4);
Assert.Fail ("#1");
} catch (ArgumentException) {
}
}
[Test]
public void Ctor_Timeout ()
{
int called = 0;
var cts = new CancellationTokenSource (TimeSpan.FromMilliseconds (20));
cts.Token.Register (() => called++);
Thread.Sleep (50);
Assert.AreEqual (1, called, "#1");
}
[Test]
public void CancelAfter ()
{
int called = 0;
var cts = new CancellationTokenSource ();
cts.Token.Register (() => called++);
cts.CancelAfter (20);
Thread.Sleep (50);
Assert.AreEqual (1, called, "#1");
}
[Test]
public void CancelAfter_Invalid ()
{
var cts = new CancellationTokenSource ();
try {
cts.CancelAfter (-9);
Assert.Fail ("#1");
} catch (ArgumentException) {
}
}
[Test]
public void CancelAfter_Disposed ()
{
int called = 0;
var cts = new CancellationTokenSource ();
cts.Token.Register (() => called++);
cts.CancelAfter (20);
cts.Dispose ();
Thread.Sleep (50);
Assert.AreEqual (0, called, "#1");
}
#endif
[Test]
public void Token ()
{
CancellationTokenSource cts = new CancellationTokenSource ();
Assert.IsTrue (cts.Token.CanBeCanceled, "#1");
Assert.IsFalse (cts.Token.IsCancellationRequested, "#2");
Assert.IsNotNull (cts.Token.WaitHandle, "#3");
}
[Test]
public void Cancel_NoRegistration ()
{
CancellationTokenSource cts = new CancellationTokenSource ();
cts.Cancel ();
}
[Test]
public void Cancel ()
{
var cts = new CancellationTokenSource ();
int called = 0;
cts.Token.Register (l => { Assert.AreEqual ("v", l); ++called; }, "v");
cts.Cancel ();
Assert.AreEqual (1, called, "#1");
called = 0;
cts.Token.Register (() => { called += 12; });
cts.Cancel ();
Assert.AreEqual (12, called, "#2");
}
[Test]
public void Cancel_Order ()
{
var cts = new CancellationTokenSource ();
var current = 0;
Action<object> a = x => { Assert.AreEqual(current, x); current++; };
cts.Token.Register (a, 2);
cts.Token.Register (a, 1);
cts.Token.Register (a, 0);
cts.Cancel ();
}
[Test]
public void CancelWithDispose ()
{
CancellationTokenSource cts = new CancellationTokenSource ();
CancellationToken c = cts.Token;
c.Register (() => {
cts.Dispose ();
});
int called = 0;
c.Register (() => {
called++;
});
cts.Cancel ();
Assert.AreEqual (1, called, "#1");
}
[Test]
public void Cancel_SingleException ()
{
var cts = new CancellationTokenSource ();
cts.Token.Register (() => { throw new ApplicationException (); });
try {
cts.Cancel ();
Assert.Fail ("#1");
} catch (AggregateException e) {
Assert.AreEqual (1, e.InnerExceptions.Count, "#2");
}
cts.Cancel ();
}
[Test]
public void Cancel_MultipleExceptions ()
{
var cts = new CancellationTokenSource ();
cts.Token.Register (() => { throw new ApplicationException ("1"); });
cts.Token.Register (() => { throw new ApplicationException ("2"); });
cts.Token.Register (() => { throw new ApplicationException ("3"); });
try {
cts.Cancel ();
Assert.Fail ("#1");
} catch (AggregateException e) {
Assert.AreEqual (3, e.InnerExceptions.Count, "#2");
}
cts.Cancel ();
try {
cts.Token.Register (() => { throw new ApplicationException ("1"); });
Assert.Fail ("#11");
} catch (ApplicationException) {
}
cts.Cancel ();
}
[Test]
public void Cancel_ExceptionOrder ()
{
var cts = new CancellationTokenSource ();
cts.Token.Register (() => { throw new ApplicationException ("1"); });
cts.Token.Register (() => { throw new ApplicationException ("2"); });
cts.Token.Register (() => { throw new ApplicationException ("3"); });
try {
cts.Cancel ();
} catch (AggregateException e) {
Assert.AreEqual (3, e.InnerExceptions.Count, "#2");
Assert.AreEqual ("3", e.InnerExceptions[0].Message, "#3");
Assert.AreEqual ("2", e.InnerExceptions[1].Message, "#4");
Assert.AreEqual ("1", e.InnerExceptions[2].Message, "#5");
}
}
[Test]
public void Cancel_MultipleException_Recursive ()
{
CancellationTokenSource cts = new CancellationTokenSource ();
CancellationToken c = cts.Token;
c.Register (() => {
cts.Cancel ();
});
c.Register (() => {
throw new ApplicationException ();
});
c.Register (() => {
throw new NotSupportedException ();
});
try {
cts.Cancel (false);
Assert.Fail ("#1");
} catch (AggregateException e) {
Assert.AreEqual (2, e.InnerExceptions.Count, "#2");
}
}
[Test]
public void Cancel_MultipleExceptionsFirstThrows ()
{
var cts = new CancellationTokenSource ();
cts.Token.Register (() => { throw new ApplicationException ("1"); });
cts.Token.Register (() => { throw new ApplicationException ("2"); });
cts.Token.Register (() => { throw new ApplicationException ("3"); });
try {
cts.Cancel (true);
Assert.Fail ("#1");
} catch (ApplicationException) {
}
cts.Cancel ();
}
[Test]
public void CreateLinkedTokenSource_InvalidArguments ()
{
var cts = new CancellationTokenSource ();
var token = cts.Token;
try {
CancellationTokenSource.CreateLinkedTokenSource (null);
Assert.Fail ("#1");
} catch (ArgumentNullException) {
}
try {
CancellationTokenSource.CreateLinkedTokenSource (new CancellationToken[0]);
Assert.Fail ("#2");
} catch (ArgumentException) {
}
}
[Test]
public void CreateLinkedTokenSource ()
{
var cts = new CancellationTokenSource ();
cts.Cancel ();
var linked = CancellationTokenSource.CreateLinkedTokenSource (cts.Token);
Assert.IsTrue (linked.IsCancellationRequested, "#1");
linked = CancellationTokenSource.CreateLinkedTokenSource (new CancellationToken ());
Assert.IsFalse (linked.IsCancellationRequested, "#2");
}
[Test]
public void Dispose ()
{
var cts = new CancellationTokenSource ();
var token = cts.Token;
cts.Dispose ();
cts.Dispose ();
var b = cts.IsCancellationRequested;
token.ThrowIfCancellationRequested ();
try {
cts.Cancel ();
Assert.Fail ("#1");
} catch (ObjectDisposedException) {
}
try {
var t = cts.Token;
Assert.Fail ("#2");
} catch (ObjectDisposedException) {
}
try {
token.Register (() => { });
Assert.Fail ("#3");
} catch (ObjectDisposedException) {
}
try {
var wh = token.WaitHandle;
Assert.Fail ("#4");
} catch (ObjectDisposedException) {
}
try {
CancellationTokenSource.CreateLinkedTokenSource (token);
Assert.Fail ("#5");
} catch (ObjectDisposedException) {
}
#if NET_4_5
try {
cts.CancelAfter (1);
Assert.Fail ("#6");
} catch (ObjectDisposedException) {
}
#endif
}
[Test]
public void RegisterThenDispose ()
{
var cts1 = new CancellationTokenSource ();
var reg1 = cts1.Token.Register (() => { throw new ApplicationException (); });
var cts2 = new CancellationTokenSource ();
var reg2 = cts2.Token.Register (() => { throw new ApplicationException (); });
Assert.AreNotEqual (cts1, cts2, "#1");
Assert.AreNotSame (cts1, cts2, "#2");
reg1.Dispose ();
cts1.Cancel ();
try {
cts2.Cancel ();
Assert.Fail ("#3");
} catch (AggregateException) {
}
}
[Test]
public void RegisterWhileCancelling ()
{
var cts = new CancellationTokenSource ();
var mre = new ManualResetEvent (false);
var mre2 = new ManualResetEvent (false);
int called = 0;
cts.Token.Register (() => {
Assert.IsTrue (cts.IsCancellationRequested, "#10");
Assert.IsTrue (cts.Token.WaitHandle.WaitOne (0), "#11");
mre2.Set ();
mre.WaitOne (3000);
called += 11;
});
var t = Task.Factory.StartNew (() => { cts.Cancel (); });
Assert.IsTrue (mre2.WaitOne (1000), "#0");
cts.Token.Register (() => { called++; });
Assert.AreEqual (1, called, "#1");
Assert.IsFalse (t.IsCompleted, "#2");
mre.Set ();
Assert.IsTrue (t.Wait (1000), "#3");
Assert.AreEqual (12, called, "#4");
}
[Test]
public void ReEntrantRegistrationTest ()
{
bool unregister = false;
bool register = false;
var source = new CancellationTokenSource ();
var token = source.Token;
Console.WriteLine ("Test1");
var reg = token.Register (() => unregister = true);
token.Register (() => reg.Dispose ());
token.Register (() => { Console.WriteLine ("Gnyah"); token.Register (() => register = true); });
source.Cancel ();
Assert.IsFalse (unregister);
Assert.IsTrue (register);
}
[Test]
public void DisposeAfterRegistrationTest ()
{
var source = new CancellationTokenSource ();
bool ran = false;
var req = source.Token.Register (() => ran = true);
source.Dispose ();
req.Dispose ();
Assert.IsFalse (ran);
}
[Test]
public void CancelLinkedTokenSource ()
{
var cts = new CancellationTokenSource ();
bool canceled = false;
cts.Token.Register (() => canceled = true);
using (var linked = CancellationTokenSource.CreateLinkedTokenSource (cts.Token))
;
Assert.IsFalse (canceled, "#1");
Assert.IsFalse (cts.IsCancellationRequested, "#2");
cts.Cancel ();
Assert.IsTrue (canceled, "#3");
}
[Test]
public void ConcurrentCancelLinkedTokenSourceWhileDisposing ()
{
ParallelTestHelper.Repeat (delegate {
var src = new CancellationTokenSource ();
var linked = CancellationTokenSource.CreateLinkedTokenSource (src.Token);
var cntd = new CountdownEvent (2);
var t1 = new Thread (() => {
if (!cntd.Signal ())
cntd.Wait (200);
src.Cancel ();
});
var t2 = new Thread (() => {
if (!cntd.Signal ())
cntd.Wait (200);
linked.Dispose ();
});
t1.Start ();
t2.Start ();
t1.Join (500);
t2.Join (500);
}, 500);
}
#if NET_4_5
[Test]
public void DisposeRace ()
{
for (int i = 0; i < 1000; ++i) {
var c1 = new CancellationTokenSource ();
using (c1) {
var wh = c1.Token.WaitHandle;
c1.CancelAfter (1);
Thread.Sleep (1);
}
}
}
#endif
}
}
#endif

View File

@@ -0,0 +1,108 @@
//
// CancellationTokenTests.cs
//
// Authors:
// Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
// Marek Safar (marek.safar@gmail.com)
//
// Copyright (c) 2009 Jérémie "Garuma" Laval
// Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if NET_4_0
using System;
using System.Threading;
using NUnit.Framework;
namespace MonoTests.System.Threading
{
[TestFixture]
public class CancellationTokenTests
{
[Test]
public void InitedWithFalseToken ()
{
CancellationToken tk = new CancellationToken (false);
Assert.IsFalse (tk.CanBeCanceled, "#1");
Assert.IsFalse (tk.IsCancellationRequested, "#2");
}
[Test]
public void InitedWithTrueToken ()
{
CancellationToken tk = new CancellationToken (true);
Assert.IsTrue (tk.CanBeCanceled, "#1");
Assert.IsTrue (tk.IsCancellationRequested, "#2");
}
[Test]
public void CancellationSourceNotCanceled ()
{
var src = new CancellationTokenSource ();
var tk = src.Token;
Assert.IsTrue (tk.CanBeCanceled);
Assert.IsFalse (tk.IsCancellationRequested);
}
[Test]
public void CancellationSourceCanceled ()
{
var src = new CancellationTokenSource ();
var tk = src.Token;
src.Cancel ();
Assert.IsTrue (tk.CanBeCanceled, "#1");
Assert.IsTrue (tk.IsCancellationRequested, "#2");
}
[Test]
public void UninitializedToken ()
{
var tk = new CancellationToken ();
Assert.IsFalse (tk.CanBeCanceled);
Assert.IsFalse (tk.IsCancellationRequested);
}
[Test]
public void NoneProperty ()
{
var n = CancellationToken.None;
Assert.IsFalse (n.CanBeCanceled, "#1");
Assert.IsFalse (n.IsCancellationRequested, "#2");
Assert.AreEqual (n, CancellationToken.None, "#3");
n.ThrowIfCancellationRequested ();
n.GetHashCode ();
}
[Test]
public void DefaultCancellationTokenRegistration ()
{
var registration = new CancellationTokenRegistration ();
// shouldn't throw
registration.Dispose ();
}
}
}
#endif

View File

@@ -0,0 +1,407 @@
2010-03-24 Jérémie Laval <jeremie.laval@gmail.com>
* SpinLockTests.cs: Add a correctness check unit test
2010-03-08 Jérémie Laval <jeremie.laval@gmail.com>
* SpinLockTests.cs: Added unit tests for SpinLock
2010-02-08 Zoltan Varga <vargaz@gmail.com>
* WaitHandleTest.cs: Add a test for #576039.
2010-02-02 Jérémie Laval <jeremie.laval@gmail.com>
* CancellationTokenTests.cs:
* LazyInitTests.cs:
* ThreadLazyTests.cs: Update namespace and tested methods
2009-12-09 Jb Evain <jbevain@novell.com>
* ThreadTest.cs: add a test for a null callback passed to
ThreadPool.QueueUserWorkItem.
2009-11-02 Jérémie Laval <jeremie.laval@gmail.com>
* ParallelTests.cs: Added unit test for Bug #536919, cleaned up.
2009-10-26 Sebastien Pouliot <sebastien@ximian.com>
* InterlockedTest.cs: Add test case for generic methods
ComapreExchange and Exchange
2009-10-25 Sebastien Pouliot <sebastien@ximian.com>
* ThreadTest.cs: Add test cases for Current[UI]Culture (not
working), Name, Join, Sleep and SpinWait
2009-10-22 Sebastien Pouliot <sebastien@ximian.com>
* EventWaitHandleTest.cs: New. Test case for EventResetMode
validation
* MonitorTest.cs: Mark existing tests as "NotWorking" since they
fail in MS FX2 (maybe they worked in 1.x?). Add more test cases
to validate the TryEnter and Wait overloaded methods.
2009-10-21 Sebastien Pouliot <sebastien@ximian.com>
* WaitHandleTest.cs: New. Add test cases for Wait[One|All|Any]
methods overloads (at least the one present in Silverlight 2)
2009-10-20 Sebastien Pouliot <sebastien@ximian.com>
* TimerTest.cs: Add more validation tests
2009-08-11 Jérémie Laval <jeremie.laval@gmail.com>
* ParallelTests.cs: Remove While test case.
* AggregateExceptionTests.cs: Moved file.
2009-07-30 Jérémie Laval <jeremie.laval@gmail.com>
* System.Threading.Tasks/TaskTest.cs:
* FutureTests.cs:
* ParallelConcurrentStackTests.cs:
* ConcurrentSkipListTests.cs:
* ConcurrentQueueTests.cs:
* ConcurrentBagTests.cs:
* ConcurrentStackTests.cs:
* BlockingCollectionTests.cs:
* ConcurrentDictionaryTests.cs:
* CollectionStressTestHelper.cs:
* ParallelConcurrentQueueTests.cs:
* CancellationTokenTests.cs:
* ManualResetEventSlimTests.cs:
* SnziTests.cs:
* SemaphoreSlimTests.cs:
* ParallelTests.cs:
* CountdownEventTests.cs:
* AggregateExceptionTests.cs:
* ThreadLazyTests.cs:
* ParallelTestHelper.cs: Add ParallelFx unit tests for System.Threading
namespace
2009-06-20 Zoltan Varga <vargaz@gmail.com>
* *.cs: Convert all tests to new-style nunit classes/methods.
2009-01-05 Zoltan Varga <vargaz@gmail.com>
* ExecutionContextTest.cs (Copy_FromThread): Disable this test, it doesn't
seem to work after the nunit upgrade.
2008-10-11 Zoltan Varga <vargaz@gmail.com>
* TimerTest.cs (TestChange): Modify a constant to avoid a random assert.
2008-07-07 Bill Holmes <billholmes54@gmail.com>
* ThreadTest.cs : Tests added for Thread.Interrupt.
Code is contributed under MIT/X11 license.
2008-06-13 Zoltan Varga <vargaz@gmail.com>
* MutexTest.cs: Reenable some mutex tests which seem to work now.
2008-06-13 Gert Driesen <drieseng@users.sourceforge.net>
* TimerTest.cs: Removed NotWorking category from TestDisposeOnCallback
test. Numbered asserts. Minor code formatting updates. Removed obsolete
comment on class.
* ThreadTest.cs: Use Assert.Fail for tests that fail on the Mono
runtime only when these tests are being executed on the Mono runtime.
2008-06-04 Zoltan Varga <vargaz@gmail.com>
* TimerTest.cs (Callback): Use Interlocked Increment to increase the
counter.
2007-12-28 Atsushi Enomoto <atsushi@ximian.com>
* ThreadTest.cs : made couple of tests fail under Windows and made
corlib tests run without timtout.
2007-12-28 Atsushi Enomoto <atsushi@ximian.com>
* ThreadTest.cs : marked TestStart() as NotDotNet. It hangs.
2007-10-21 Gert Driesen <drieseng@users.sourceforge.net>
* ThreadTest.cs: On 2.0 profile, enable > 0 tests for GetHashCode.
Added test that asserts if the hashcode of two threads is distinct.
2007-10-20 Raja R Harinath <harinath@gmail.com>
* TimerTest.cs (TestHeavyCreationLoad): Don't shadow a variable name.
2007-10-19 Dick Porter <dick@ximian.com>
* ThreadTest.cs: Re-enable ManagedThreadId test too
2007-10-19 Dick Porter <dick@ximian.com>
* ThreadTest.cs: Re-enable GetHashCodeTest
2007-10-05 Dick Porter <dick@ximian.com>
* ThreadTest.cs: Disable GetHashCodeTest while I figure out why
GetHashCode sometimes returns 0.
2007-09-25 Dick Porter <dick@ximian.com>
* ThreadTest.cs: Enable GetHashCodeTest
2007-09-18 Gert Driesen <drieseng@users.sourceforge.net>
* ThreadTest.cs: Added GetHashCode test for bug #325566.
2007-09-05 Gert Driesen <drieseng@users.sourceforge.net>
* ThreadTest.cs: Added test for bug #82700. Re-enabled and fixed some
tests that pass on my two boxes. Shoot me if these break the buildbots.
Cleaned up some tests.
2007-08-10 Gert Driesen <drieseng@users.sourceforge.net>
* ThreadTest.cs: Enabled test for bug #81658, and uncommented code
that relies on that fix.
2007-07-22 Gert Driesen <drieseng@users.sourceforge.net>
* AutoResetEventTest.cs: Added test for verifying effect of assigning
new SafeWaitHandle on the previous one. Use meaningful names for
tests. Avoid unref warning. Removed usage of deprecated Assertion
class. Spaces to tabs.
2007-07-21 Miguel de Icaza <miguel@novell.com>
* AutoResetEventTest.cs: Integrated test based on Gert's email
(only the first chunk).
2007-07-08 Gert Driesen <drieseng@users.sourceforge.net>
* ThreadTest.cs: Removed tests for bug #81930, since other tests can
break these by changing the CurrentCulture or CurrentUICulture.
Instead I've added a standalone test for this (in the gert module).
2007-06-24 Gert Driesen <drieseng@users.sourceforge.net>
* ThreadTest.cs: Added tests for bug #81930.
2007-06-08 Gert Driesen <drieseng@users.sourceforge.net>
* ThreadTest.cs: Enabled test for bug #81720.
2007-05-23 Gert Driesen <drieseng@users.sourceforge.net>
* ThreadTest.cs: Added test for bug #81720. Improved test for
bug #81658. Added test for changing ApartmentState on background
thread.
2007-05-17 Gert Driesen <drieseng@users.sourceforge.net>
* ThreadTest.cs: Use Assert instead of deprecated Assertion class.
Code formatting. Added test for bug #81658.
2007-05-16 Gert Driesen <drieseng@users.sourceoforge.net>
* ThreadTest.cs: Fix build using csc 1.x.
2007-05-09 Jonathan Chambers <joncham@gmail.com>
* ThreadTest.cs: Add ApartmentState related tests.
2007-04-03 Gert Driesen <drieseng@users.sourceforge.net>
* MutexTest.cs: Enabled test for bug #79358.
2006-12-13 Gert Driesen <drieseng@users.sourceforge.net>
* MutexTest.cs: Added test for bug #79358. Code formatting, no longer
derive from (deprecated) TestCase.
2006-06-14 Sebastien Pouliot <sebastien@ximian.com>
* ExecutionContextTest.cs: Changed Run test to execute only under
CAS until bug #78306 (CompressedStack) is fixed.
2006-06-04 Zoltan Varga <vargaz@gmail.com>
* InterlockedTest.cs: Fix Interlocked.Add tests.
2006-04-30 Gert Driesen <drieseng@users.sourceforge.net>
* TimerTest.cs: Added test for bug #78208. Marked individual tests
NotWorking instead of the test class to enable test for bug #78208.
2006-01-18 Atsushi Enomoto <atsushi@ximian.com>
* ThreadTest.cs : mark not-working tests as [Ignore] since it blocks
run-test-ondotnet under 2.0 profile.
2006-01-18 Atsushi Enomoto <atsushi@ximian.com>
* MutexTest.cs : Marked TestWaitAndFoget1 as [Ignore]. Under
.NET 2.0 it breaks nunit-console (breaks its own AppDomain).
2005-10-06 Sebastien Pouliot <sebastien@ximian.com>
* ThreadTest.cs: Added regression test for #76332 when an IPrincipal
instance should be copied in any new thread created.
2005-06-30 Ben Maurer <bmaurer@ximian.com>
* MutexTest.cs: Redisable. They didn't work so well ;-(.
2005-06-28 Ben Maurer <bmaurer@ximian.com>
* MutexTest.cs: Re-enable the mutex tests. They seem to work for
me now when I ran them in a loop on the smp box.
2005-06-06 Gonzalo Paniagua Javier <gonzalo@ximian.com>
* ThreadTest.cs: sanitize waiting for a thread that might be already
done. Added test for Thread.Start called after thread.Abort, which used
to segfault.
2005-05-05 Gonzalo Paniagua Javier <gonzalo@ximian.com>
* MonitorTest.cs: a pair of tests for Monitor.
2005-04-30 Gonzalo Paniagua Javier <gonzalo@ximian.com>
* AutoResetEventTest.cs: test for AutoResetEvent.
2005-03-28 Sebastien Pouliot <sebastien@ximian.com>
* CompressedStackCas.cs: New. CAS unit tests for CompressedStack.
* CompressedStackTest.cs: New. Unit tests for CompressedStack.
* ExecutionContextCas.cs: New. CAS unit tests for ExecutionContext.
* ExecutionContextTest.cs: New. Unit tests for ExecutionContext.
2005-03-24 Sebastien Pouliot <sebastien@ximian.com>
* MutexCas.cs: New. CAS unit tests for Mutex.
* ThreadCas.cs: New. CAS unit tests for Thread.
* WaitHandleCas.cs: New. CAS unit tests for WaitHandle.
2005-02-20 Zoltan Varga <vargaz@freemail.hu>
* InterlockedTest.cs: Enable 2.0 tests.
* InterlockedTest.cs: New file. Tests from
Luca Barbieri (luca.barbieri@gmail.com).
2005-02-16 Ben Maurer <bmaurer@ximian.com>
* TimerTest.cs: Disable this test. It seems to be completely
unreliable, likely because it depends on a race. See comment in
the source.
2005-01-31 Nick Drochak <ndrochak@ieee.com>
* ThreadTest.cs: SuspendAbort is not working it seems.
2005-01-18 Nick Drochak <ndrochak@ieee.com>
* ThreadTest.cs: Thread.Priority is a MonoTODO. Ignore Test.
2004-09-22 Lluis Sanchez Gual <lluis@novell.com>
* ThreadTest.cs, MutexTest.cs: Don't leave any thread alive, even if the
thread fails. Added a timeout to active waits.
2004-08-25 Nick Drochak <ndrochak@ieee.com>
* ThreadTest.cs: Some tests hang on MS.NET so ignore them.
2004-06-22 Dick Porter <dick@ximian.com>
* MutexTest.cs: No need to ignore these tests now
* ThreadTest.cs: You can't Start() a thread that's been aborted.
Improve state tests.
2004-06-17 Lluis Sanchez Gual <lluis@ximian.com>
* ThreadTest.cs: Improved test.
2004-06-15 Lluis Sanchez Gual <lluis@ximian.com>
* TimerTest.cs: Added more tests.
* ThreadTest.cs: Added new tests for Thread.Suspend.
2004-06-10 Lluis Sanchez Gual <lluis@ximian.com>
* ThreadTest.cs: Removed Ignore attribute from several threading tests that
failed because of Thread.Abort.
2004-05-01 Nick Drochak <ndrochak@gol.com>
* ThreadTest.cs: Un-ignore some tests that seem to run pretty well
now. Getting one failure from these, but at least they run without
crasing, or trowing some nasty _wapi exception thingy.
2004-04-27 Nick Drochak <ndrochak@ieee.org>
* ReaderWriterLockTest.cs: Remove compiler warnings.
2004-04-13 Lluis Sanchez Gual <lluis@ximian.com>
* ReaderWriterLockTest.cs: Added more tests for bugs 55911 and 55909.
2004-04-13 Sebastien Pouliot <sebastien@ximian.com>
* ThreadTest.cs: Removed [Ignore] on WindowsPrincipal test. Adjusted
CurrentPrincipal tests to work on both Windows and Linux.
2004-04-09 Zoltan Varga <vargaz@freemail.hu>
* TimerTest.cs: Beginnings of regression tests for the Timer class.
2004-04-07 Lluis Sanchez Gual <lluis@ximian.com>
* ReaderWriterLockTest.cs: Added one more test.
2004-04-06 Lluis Sanchez Gual <lluis@ximian.com>
* ReaderWriterLockTest.cs: New tests for System.Threading.ReaderWriterLock.
2004-03-19 David Sheldon <dave-mono@earth.li>
* ThreadTest.cs: Removed Ignore attributes from
CurrentPrincipal_PrincipalPolicy_NoPrincipal and
CurrentPrincipal_PrincipalPolicy_UnauthenticatedPrincipal
Now that bug 54041 is fixed, and they wont livelock.
2004-02-05 Sebastien Pouliot <sebastien@ximian.com>
* ThreadTest.cs: Added unit tests for CurrentPrincipal.
2003-01-28 Nick Drochak <ndrochak@gol.com>
* MutexTest.cs: Ignore tests that hang mono.
* ThreadTest.cs: Ignore tests that hang mono.
2003/01/23 Nick Drochak <ndrochak@gol.com>
* ThreadTest.cs: Test for alternate possibilities
2003-01-13 Nick Drochak <ndrochak@gol.com>
* MutexTest.cs: Disable some tests that case unhandled exceptions
on MS.NET.
2002-12-21 Nick Drochak <ndrochak@gol.com>
* all: make tests build and run under nunit2
2002-11-29 Eduardo Garcia Cebollero <kiwnix@yahoo.es>
* MutexTest.cs : New suite for Mutex.
2002-11-23 Eduardo Garcia Cebollero <kiwnix@yahoo.es>
* ThreadTest.cs : New suite for Thread.
* AllTests.cs : Add the new suite.

View File

@@ -0,0 +1,109 @@
//
// CompressedStackCas.cs - CAS Unit Tests for CompressedStack
//
// Author:
// Sebastien Pouliot (sebastien@ximian.com)
//
// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Note: the class existed in 1.1 but the only thing we know about it is that
// it has a finalizer ;-)
#if NET_2_0
using System;
using System.Security;
using System.Security.Permissions;
using System.Threading;
using NUnit.Framework;
namespace MonoCasTests.System.Threading {
// NOTES
// The tests will fails on 2.0 beta 1 (and a few CTP afterwards) because it relies
// on a LinkDemand for ECMA key (and identity permissions now support unrestricted).
[TestFixture]
[Category ("CAS")]
public class CompressedStackCas {
static bool success;
static void Callback (object o)
{
new SecurityPermission (SecurityPermissionFlag.UnmanagedCode).Demand ();
success = (bool)o;
}
[SetUp]
public void SetUp ()
{
if (!SecurityManager.SecurityEnabled)
Assert.Ignore ("SecurityManager isn't enabled");
success = false;
}
[Test]
public void Run_Empty ()
{
Assert.IsFalse (success, "pre-check");
CompressedStack.Run (CompressedStack.Capture (), new ContextCallback (Callback), true);
Assert.IsTrue (success, "post-check");
}
[SecurityPermission (SecurityAction.Deny, UnmanagedCode = true)]
private CompressedStack GetCompressedStackUnmanaged ()
{
return CompressedStack.Capture ();
// the Deny disappears with this stack frame but we got a capture of it
}
private void Thread_Run_UnmanagedCode ()
{
bool result = false;
Assert.IsFalse (success, "pre-check");
try {
CompressedStack cs = GetCompressedStackUnmanaged ();
// run with the captured security stack (i.e. deny unmanaged)
CompressedStack.Run (cs, new ContextCallback (Callback), true);
}
catch (SecurityException) {
result = true;
}
finally {
Assert.IsFalse (success, "post-check");
Assert.IsTrue (result, "Result");
}
}
[Test]
public void Run_UnmanagedCode ()
{
Thread t = new Thread (new ThreadStart (Thread_Run_UnmanagedCode));
t.Start ();
t.Join ();
}
}
}
#endif

View File

@@ -0,0 +1,143 @@
//
// CompressedStackTest.cs - NUnit Test Cases for CompressedStack
//
// Author:
// Sebastien Pouliot (sebastien@ximian.com)
//
// Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#if !MOBILE
using System;
using System.Runtime.Serialization;
using System.Security;
using System.Threading;
using NUnit.Framework;
namespace MonoTests.System.Threading {
// NOTES
// The tests will fails on 2.0 beta 1 (and a few CTP afterwards) because it relies
// on a LinkDemand for ECMA key (and identity permissions now support unrestricted).
[TestFixture]
public class CompressedStackTest {
static bool success;
static void Callback (object o)
{
success = (bool) o;
}
[SetUp]
public void SetUp ()
{
success = false;
Thread.CurrentThread.SetCompressedStack (null);
}
[Test]
public void Capture ()
{
CompressedStack cs1 = CompressedStack.Capture ();
Assert.IsNotNull (cs1, "Capture-1");
CompressedStack cs2 = CompressedStack.Capture ();
Assert.IsNotNull (cs2, "Capture-2");
Assert.IsFalse (cs1.Equals (cs2), "cs1.Equals (cs2)");
Assert.IsFalse (cs2.Equals (cs1), "cs2.Equals (cs1)");
Assert.IsFalse (cs1.GetHashCode () == cs2.GetHashCode (), "GetHashCode");
}
[Test]
public void CreateCopy ()
{
CompressedStack cs1 = CompressedStack.Capture ();
CompressedStack cs2 = cs1.CreateCopy ();
Assert.IsFalse (cs1.Equals (cs2), "cs1.Equals (cs2)");
Assert.IsFalse (cs2.Equals (cs1), "cs2.Equals (cs1)");
Assert.IsFalse (cs1.GetHashCode () == cs2.GetHashCode (), "GetHashCode");
Assert.IsFalse (Object.ReferenceEquals (cs1, cs2), "ReferenceEquals");
}
[Test]
public void GetCompressedStack ()
{
CompressedStack cs1 = CompressedStack.GetCompressedStack ();
Assert.IsNotNull (cs1, "GetCompressedStack");
CompressedStack cs2 = CompressedStack.Capture ();
Assert.IsNotNull (cs2, "Capture");
Assert.IsFalse (cs1.Equals (cs2), "cs1.Equals (cs2)");
Assert.IsFalse (cs2.Equals (cs1), "cs2.Equals (cs1)");
Assert.IsFalse (cs1.GetHashCode () == cs2.GetHashCode (), "GetHashCode");
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void GetObjectData_Null ()
{
StreamingContext sc = new StreamingContext ();
CompressedStack cs = CompressedStack.Capture ();
cs.GetObjectData (null, sc);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void Run_Null ()
{
CompressedStack.Run (null, new ContextCallback (Callback), true);
}
[Test]
public void Run_Capture ()
{
Assert.IsFalse (success, "pre-check");
CompressedStack.Run (CompressedStack.Capture (), new ContextCallback (Callback), true);
Assert.IsTrue (success, "post-check");
}
[Test]
public void Run_GetCompressedStack ()
{
Assert.IsFalse (success, "pre-check");
CompressedStack.Run (CompressedStack.GetCompressedStack (), new ContextCallback (Callback), true);
Assert.IsTrue (success, "post-check");
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void Run_Thread ()
{
// this is because Thread.CurrentThread.GetCompressedStack () returns null for an empty
// compressed stack while CompressedStack.GetCompressedStack () return "something" empty ;-)
CompressedStack.Run (Thread.CurrentThread.GetCompressedStack (), new ContextCallback (Callback), true);
}
}
}
#endif

View File

@@ -0,0 +1,399 @@
// CountdownEventTests.cs
//
// Authors:
// Marek Safar <marek.safar@gmail.com>
//
// Copyright (c) 2008 Jérémie "Garuma" Laval
// Copyright 2011 Xamarin Inc (http://www.xamarin.com).
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//
#if NET_4_0
using System;
using System.Threading;
using NUnit.Framework;
using MonoTests.System.Threading.Tasks;
namespace MonoTests.System.Threading
{
[TestFixtureAttribute]
public class CountdownEventTests
{
[Test]
public void Constructor_Invalid ()
{
try {
new CountdownEvent (-2);
Assert.Fail ("#1");
} catch (ArgumentOutOfRangeException) {
}
}
[Test]
public void Constructor_Zero ()
{
var ce = new CountdownEvent (0);
Assert.IsTrue (ce.IsSet, "#1");
Assert.AreEqual (0, ce.InitialCount, "#2");
Assert.IsTrue (ce.Wait (0), "#3");
}
[Test]
public void Constructor_Max ()
{
new CountdownEvent (int.MaxValue);
}
[Test]
public void AddCount_Invalid ()
{
var ev = new CountdownEvent (1);
try {
ev.AddCount (0);
Assert.Fail ("#1");
} catch (ArgumentOutOfRangeException) {
}
try {
ev.AddCount (-1);
Assert.Fail ("#2");
} catch (ArgumentOutOfRangeException) {
}
}
[Test]
public void AddCount_HasBeenSet ()
{
var ev = new CountdownEvent (0);
try {
ev.AddCount (1);
Assert.Fail ("#1");
} catch (InvalidOperationException) {
}
ev = new CountdownEvent (1);
Assert.IsTrue (ev.Signal (), "#2");
try {
ev.AddCount (1);
Assert.Fail ("#3");
} catch (InvalidOperationException) {
}
}
[Test]
public void AddCountSignalStressTestCase ()
{
var evt = new CountdownEvent (5);
int count = 0;
ParallelTestHelper.ParallelStressTest (evt, delegate (CountdownEvent e) {
int num = Interlocked.Increment (ref count);
if (num % 2 == 0)
e.AddCount ();
else
e.Signal ();
}, 7);
Assert.AreEqual (4, evt.CurrentCount, "#1");
Assert.IsFalse (evt.IsSet, "#2");
}
[Test]
public void InitialTestCase()
{
var evt = new CountdownEvent (5);
Assert.AreEqual(5, evt.InitialCount, "#1");
evt.AddCount();
evt.Signal(3);
Assert.AreEqual(5, evt.InitialCount, "#2");
}
[Test]
public void CurrentCountTestCase()
{
var evt = new CountdownEvent (5);
Assert.AreEqual(5, evt.CurrentCount, "#1");
evt.AddCount();
Assert.AreEqual(6, evt.CurrentCount, "#2");
evt.TryAddCount(2);
Assert.AreEqual(8, evt.CurrentCount, "#3");
evt.Signal(4);
Assert.AreEqual(4, evt.CurrentCount, "#4");
evt.Reset();
Assert.AreEqual(5, evt.CurrentCount, "#5");
}
[Test]
public void Dispose ()
{
var ce = new CountdownEvent (1);
ce.Dispose ();
Assert.AreEqual (1, ce.CurrentCount, "#0a");
Assert.AreEqual (1, ce.InitialCount, "#0b");
Assert.IsFalse (ce.IsSet, "#0c");
try {
ce.AddCount ();
Assert.Fail ("#1");
} catch (ObjectDisposedException) {
}
try {
ce.Reset ();
Assert.Fail ("#2");
} catch (ObjectDisposedException) {
}
try {
ce.Signal ();
Assert.Fail ("#3");
} catch (ObjectDisposedException) {
}
try {
ce.TryAddCount ();
Assert.Fail ("#4");
} catch (ObjectDisposedException) {
}
try {
ce.Wait (5);
Assert.Fail ("#4");
} catch (ObjectDisposedException) {
}
try {
var v = ce.WaitHandle;
Assert.Fail ("#5");
} catch (ObjectDisposedException) {
}
}
[Test]
public void Dispose_Double ()
{
var ce = new CountdownEvent (1);
ce.Dispose ();
ce.Dispose ();
}
[Test]
public void IsSetTestCase()
{
var evt = new CountdownEvent (5);
Assert.IsFalse(evt.IsSet, "#1");
evt.Signal(5);
Assert.IsTrue(evt.IsSet, "#2");
evt.Reset();
Assert.IsFalse(evt.IsSet, "#3");
}
[Test]
public void Reset_Invalid ()
{
var ev = new CountdownEvent (1);
try {
ev.Reset (-1);
Assert.Fail ("#1");
} catch (ArgumentOutOfRangeException) {
Assert.AreEqual (1, ev.CurrentCount, "#1a");
}
}
[Test]
public void Reset_FullInitialized ()
{
var ev = new CountdownEvent (0);
Assert.IsTrue (ev.IsSet, "#1");
Assert.AreEqual (0, ev.CurrentCount, "#2");
ev.Reset (4);
Assert.IsFalse (ev.IsSet, "#3");
Assert.AreEqual (4, ev.CurrentCount, "#4");
Assert.IsFalse (ev.Wait (0), "#5");
}
[Test]
public void Reset_Zero ()
{
var ev = new CountdownEvent (1);
Assert.IsFalse (ev.IsSet, "#1");
ev.Reset (0);
Assert.IsTrue (ev.IsSet, "#2");
Assert.IsTrue (ev.Wait (0), "#3");
Assert.AreEqual (0, ev.CurrentCount, "#4");
}
[Test]
public void Signal_Invalid ()
{
var ev = new CountdownEvent (1);
try {
ev.Signal (0);
Assert.Fail ("#1");
} catch (ArgumentOutOfRangeException) {
Assert.AreEqual (1, ev.CurrentCount, "#1a");
}
try {
ev.Signal (-1);
Assert.Fail ("#2");
} catch (ArgumentOutOfRangeException) {
Assert.AreEqual (1, ev.CurrentCount, "#2a");
}
}
[Test]
public void Signal_Negative ()
{
var ev = new CountdownEvent (1);
try {
ev.Signal (2);
Assert.Fail ("#1");
} catch (InvalidOperationException) {
Assert.AreEqual (1, ev.CurrentCount, "#1a");
}
ev.Signal ();
try {
ev.Signal ();
Assert.Fail ("#2");
} catch (InvalidOperationException) {
Assert.AreEqual (0, ev.CurrentCount, "#2a");
}
}
[Test]
public void Signal_Concurrent ()
{
for (int r = 0; r < 100; ++r) {
using (var ce = new CountdownEvent (500)) {
for (int i = 0; i < ce.InitialCount; ++i) {
ThreadPool.QueueUserWorkItem (delegate {
ce.Signal ();
});
}
Assert.IsTrue (ce.Wait (1000), "#1");
}
}
}
[Test]
public void TryAddCountTestCase()
{
var evt = new CountdownEvent (5);
Assert.IsTrue(evt.TryAddCount(2), "#1");
evt.Signal(7);
Assert.IsFalse(evt.TryAddCount(), "#2");
}
[Test]
public void TryAddCount_Invalid ()
{
var ev = new CountdownEvent (1);
try {
ev.TryAddCount (0);
Assert.Fail ("#1");
} catch (ArgumentOutOfRangeException) {
}
try {
ev.TryAddCount (-1);
Assert.Fail ("#2");
} catch (ArgumentOutOfRangeException) {
}
}
[Test]
public void TryAddCount_HasBeenSet ()
{
var ev = new CountdownEvent (0);
Assert.IsFalse (ev.TryAddCount (1), "#1");
ev = new CountdownEvent (1);
ev.Signal ();
Assert.IsFalse (ev.TryAddCount (1), "#2");
ev = new CountdownEvent (2);
ev.Signal (2);
Assert.IsFalse (ev.TryAddCount (66), "#3");
}
[Test]
public void WaitTestCase()
{
var evt = new CountdownEvent (5);
int count = 0;
bool s = false;
ParallelTestHelper.ParallelStressTest(evt, delegate (CountdownEvent e) {
if (Interlocked.Increment(ref count) % 2 == 0) {
Thread.Sleep(100);
while(!e.IsSet)
e.Signal();
} else {
e.Wait();
s = true;
}
}, 3);
Assert.IsTrue(s, "#1");
Assert.IsTrue(evt.IsSet, "#2");
}
[Test]
public void ResetTest ()
{
var evt = new CountdownEvent (5);
Assert.AreEqual (5, evt.CurrentCount);
evt.Signal ();
Assert.AreEqual (4, evt.CurrentCount);
evt.Reset ();
Assert.AreEqual (5, evt.CurrentCount);
Assert.AreEqual (5, evt.InitialCount);
evt.Signal ();
evt.Signal ();
Assert.AreEqual (3, evt.CurrentCount);
Assert.AreEqual (5, evt.InitialCount);
evt.Reset (10);
Assert.AreEqual (10, evt.CurrentCount);
Assert.AreEqual (10, evt.InitialCount);
}
}
}
#endif

View File

@@ -0,0 +1,51 @@
//
// EventWaitHandleTest.cs - NUnit Test Cases for EventWaitHandle
//
// Author:
// Sebastien Pouliot (sebastien@ximian.com)
//
// Copyright (C) 2009 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#if NET_2_0
using System;
using System.Threading;
using NUnit.Framework;
namespace MonoTests.System.Threading {
[TestFixture]
public class EventWaitHandleTest {
[Test]
[ExpectedException (typeof (ArgumentException))]
public void EventWaitHandle_InvalidEventResetMode ()
{
new EventWaitHandle (true, (EventResetMode) Int32.MinValue);
}
}
}
#endif

View File

@@ -0,0 +1,172 @@
//
// ExecutionContextCas.cs - CAS Unit Tests for ExecutionContext
//
// Author:
// Sebastien Pouliot (sebastien@ximian.com)
//
// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#if NET_2_0
using System;
using System.Security;
using System.Security.Permissions;
using System.Threading;
using NUnit.Framework;
namespace MonoCasTests.System.Threading {
[TestFixture]
[Category ("CAS")]
public class ExecutionContextCas {
static bool success;
static void Callback (object o)
{
new SecurityPermission (SecurityPermissionFlag.UnmanagedCode).Demand ();
success = (bool)o;
}
[SetUp]
public void SetUp ()
{
if (!SecurityManager.SecurityEnabled)
Assert.Ignore ("SecurityManager isn't enabled");
success = false;
}
[TearDown]
public void TearDown ()
{
if (ExecutionContext.IsFlowSuppressed ())
ExecutionContext.RestoreFlow ();
}
private void Thread_Run_Empty ()
{
Assert.IsFalse (success, "pre-check");
ExecutionContext.Run (ExecutionContext.Capture (), new ContextCallback (Callback), true);
Assert.IsTrue (success, "post-check");
}
[Test]
public void Run_Empty ()
{
Thread t = new Thread (new ThreadStart (Thread_Run_Empty));
t.Start ();
t.Join ();
}
[SecurityPermission (SecurityAction.Deny, UnmanagedCode = true)]
private ExecutionContext GetExecutionContextUnmanaged ()
{
return ExecutionContext.Capture ();
// the Deny disappears with this stack frame but we got a capture of it
}
private void Thread_Run_UnmanagedCode ()
{
bool result = false;
Assert.IsFalse (success, "pre-check");
try {
ExecutionContext ec = GetExecutionContextUnmanaged ();
// run with the captured security stack (i.e. deny unmanaged)
ExecutionContext.Run (ec, new ContextCallback (Callback), true);
}
catch (SecurityException) {
result = true;
}
finally {
Assert.IsFalse (success, "post-check");
Assert.IsTrue (result, "Result");
}
}
[Test]
public void Run_UnmanagedCode ()
{
Thread t = new Thread (new ThreadStart (Thread_Run_UnmanagedCode));
t.Start ();
t.Join ();
}
private void Thread_Run_UnmanagedCode_SuppressFlow_BeforeCapture ()
{
bool result = false;
Assert.IsFalse (success, "pre-check");
AsyncFlowControl afc = ExecutionContext.SuppressFlow ();
try {
ExecutionContext ec = GetExecutionContextUnmanaged ();
ExecutionContext.Run (ec, new ContextCallback (Callback), true);
}
catch (InvalidOperationException) {
result = true;
}
finally {
Assert.IsFalse (success, "post-check");
afc.Undo ();
Assert.IsTrue (result, "Result");
}
}
[Test]
public void Run_UnmanagedCode_SuppressFlow_BeforeCapture ()
{
Thread t = new Thread (new ThreadStart (Thread_Run_UnmanagedCode_SuppressFlow_BeforeCapture));
t.Start ();
t.Join ();
}
private void Thread_Run_UnmanagedCode_SuppressFlow_AfterCapture ()
{
bool result = false;
Assert.IsFalse (success, "pre-check");
ExecutionContext ec = GetExecutionContextUnmanaged ();
AsyncFlowControl afc = ExecutionContext.SuppressFlow ();
try {
ExecutionContext.Run (ec, new ContextCallback (Callback), true);
}
catch (SecurityException) {
result = true;
}
finally {
Assert.IsFalse (success, "post-check");
afc.Undo ();
Assert.IsTrue (result, "Result");
}
}
[Test]
public void Run_UnmanagedCode_SuppressFlow_AfterCapture ()
{
Thread t = new Thread (new ThreadStart (Thread_Run_UnmanagedCode_SuppressFlow_AfterCapture));
t.Start ();
t.Join ();
}
}
}
#endif

View File

@@ -0,0 +1,295 @@
//
// ExecutionContextTest.cs - NUnit tests for ExecutionContext
//
// Author:
// Sebastien Pouliot <sebastien@ximian.com>
//
// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.Runtime.Remoting.Messaging;
#if NET_2_0
using System;
using System.Security;
using System.Threading;
using NUnit.Framework;
namespace MonoTests.System.Threading {
[TestFixture]
public class ExecutionContextTest {
static bool success;
static void Callback (object o)
{
success = (bool)o;
}
public class CallContextValue : ILogicalThreadAffinative {
public object Value { get; set; }
public CallContextValue (object value)
{
this.Value = value;
}
}
[SetUp]
public void SetUp ()
{
success = false;
}
[TearDown]
public void TearDown ()
{
if (ExecutionContext.IsFlowSuppressed ())
ExecutionContext.RestoreFlow ();
CallContext.FreeNamedDataSlot ("testlc");
}
[Test]
[Category("MobileNotWorking")]
public void LogicalGetData_SetData()
{
var value = "a";
CallContext.SetData ("testlc", value);
var capturedValue = CallContext.LogicalGetData ("testlc");
Assert.IsNull (capturedValue);
}
[Test]
[Category("MobileNotWorking")]
public void LogicalGetData_SetDataLogicalThreadAffinative()
{
var value = new CallContextValue ("a");
CallContext.SetData ("testlc", value);
var capturedValue = CallContext.LogicalGetData ("testlc");
Assert.AreEqual (value, capturedValue);
}
[Test]
[Category("MobileNotWorking")]
public void GetData_SetLogicalData()
{
var value = "a";
CallContext.LogicalSetData ("testlc", value);
var capturedValue = CallContext.GetData ("testlc");
Assert.AreEqual (value, capturedValue);
}
[Test]
[Category("MobileNotWorking")]
public void CaptureLogicalCallContext()
{
var value = "Tester";
object capturedValue = null;
CallContext.LogicalSetData ("testlc", value);
ExecutionContext ec = ExecutionContext.Capture ();
Assert.IsNotNull (ec, "Capture");
Assert.AreEqual (value, CallContext.LogicalGetData ("testlc"));
CallContext.LogicalSetData ("testlc", null);
ExecutionContext.Run (ec, new ContextCallback (new Action<object> ((data) => {
capturedValue = CallContext.LogicalGetData ("testlc");
})), null);
Assert.AreEqual (value, capturedValue);
Assert.AreNotEqual (value, CallContext.LogicalGetData ("testlc"));
}
[Test]
[Category ("MobileNotWorking")]
public void CaptureCallContext ()
{
var value = new CallContextValue (true);
object capturedValue = null;
CallContext.SetData ("testlc", value);
ExecutionContext ec = ExecutionContext.Capture ();
Assert.IsNotNull (ec, "Capture");
Assert.AreEqual (value, CallContext.GetData ("testlc"));
CallContext.SetData ("testlc", null);
ExecutionContext.Run (ec, new ContextCallback (new Action<object> ((data) => {
capturedValue = CallContext.GetData ("testlc");
})), null);
Assert.AreEqual (value, capturedValue);
Assert.AreNotEqual (value, CallContext.GetData ("testlc"));
}
[Test]
[Category("MobileNotWorking")]
public void Capture ()
{
ExecutionContext ec = ExecutionContext.Capture ();
Assert.IsNotNull (ec, "Capture");
AsyncFlowControl afc = ExecutionContext.SuppressFlow ();
Assert.IsTrue (ExecutionContext.IsFlowSuppressed (), "IsFlowSuppressed-1");
try {
ec = ExecutionContext.Capture ();
Assert.IsNull (ec, "Capture with SuppressFlow");
}
finally {
afc.Undo ();
}
}
[Test]
[Category("MobileNotWorking")]
public void Copy ()
{
ExecutionContext ec = ExecutionContext.Capture ();
Assert.IsNotNull (ec, "Capture");
ExecutionContext copy = ec.CreateCopy ();
Assert.IsNotNull (copy, "Copy of Capture");
Assert.IsFalse (ec.Equals (copy));
Assert.IsFalse (copy.Equals (ec));
Assert.IsFalse (Object.ReferenceEquals (ec, copy));
ExecutionContext copy2nd = copy.CreateCopy ();
Assert.IsNotNull (copy2nd, "2nd level copy of Capture");
}
[Test]
[ExpectedException (typeof (InvalidOperationException))]
// The context might be the result of capture so no exception is thrown
[Category ("NotWorking")]
public void Copy_FromThread ()
{
ExecutionContext ec = Thread.CurrentThread.ExecutionContext;
Assert.IsNotNull (ec, "Thread.CurrentThread.ExecutionContext");
ExecutionContext copy = ec.CreateCopy ();
}
[Test]
[Category("MobileNotWorking")]
public void IsFlowSuppressed ()
{
Assert.IsFalse (ExecutionContext.IsFlowSuppressed (), "IsFlowSuppressed-1");
AsyncFlowControl afc = ExecutionContext.SuppressFlow ();
Assert.IsTrue (ExecutionContext.IsFlowSuppressed (), "IsFlowSuppressed-2");
afc.Undo ();
Assert.IsFalse (ExecutionContext.IsFlowSuppressed (), "IsFlowSuppressed-3");
}
[Test]
[ExpectedException (typeof (InvalidOperationException))]
[Category("MobileNotWorking")]
public void RestoreFlow_None ()
{
ExecutionContext.RestoreFlow ();
}
[Test]
[Category("MobileNotWorking")]
public void RestoreFlow_SuppressFlow ()
{
Assert.IsFalse (ExecutionContext.IsFlowSuppressed (), "IsFlowSuppressed-1");
ExecutionContext.SuppressFlow ();
Assert.IsTrue (ExecutionContext.IsFlowSuppressed (), "IsFlowSuppressed-2");
ExecutionContext.RestoreFlow ();
Assert.IsFalse (ExecutionContext.IsFlowSuppressed (), "IsFlowSuppressed-3");
}
[Test]
[Category ("CAS")] // since r60298 the SecurityContext is only captured if the security manager is active
public void Run () // see bug #78306 for details
{
Assert.IsFalse (success, "pre-check");
ExecutionContext.Run (ExecutionContext.Capture (), new ContextCallback (Callback), true);
Assert.IsTrue (success, "post-check");
}
[Test]
[ExpectedException (typeof (InvalidOperationException))]
[Category("MobileNotWorking")]
public void Run_SuppressFlow ()
{
Assert.IsFalse (ExecutionContext.IsFlowSuppressed ());
AsyncFlowControl afc = ExecutionContext.SuppressFlow ();
Assert.IsTrue (ExecutionContext.IsFlowSuppressed ());
try {
ExecutionContext.Run (ExecutionContext.Capture (), new ContextCallback (Callback), "Hello world.");
}
finally {
afc.Undo ();
}
}
[Test]
[Category("MobileNotWorking")]
public void SuppressFlow ()
{
Assert.IsFalse (ExecutionContext.IsFlowSuppressed (), "IsFlowSuppressed-1");
AsyncFlowControl afc = ExecutionContext.SuppressFlow ();
Assert.IsTrue (ExecutionContext.IsFlowSuppressed (), "IsFlowSuppressed-3");
afc.Undo ();
Assert.IsFalse (ExecutionContext.IsFlowSuppressed (), "IsFlowSuppressed-4");
}
[Test]
[ExpectedException (typeof (InvalidOperationException))]
[Category("MobileNotWorking")]
public void SuppressFlow_Two_Undo ()
{
Assert.IsFalse (ExecutionContext.IsFlowSuppressed (), "IsFlowSuppressed-1");
AsyncFlowControl afc = ExecutionContext.SuppressFlow ();
Assert.IsTrue (ExecutionContext.IsFlowSuppressed (), "IsFlowSuppressed-2");
AsyncFlowControl afc2 = ExecutionContext.SuppressFlow ();
Assert.IsTrue (ExecutionContext.IsFlowSuppressed (), "IsFlowSuppressed-3");
afc2.Undo ();
// note: afc2 Undo return to the original (not the previous) state
Assert.IsFalse (ExecutionContext.IsFlowSuppressed (), "IsFlowSuppressed-4");
// we can't use the first AsyncFlowControl
afc.Undo ();
}
}
}
#endif

View File

@@ -0,0 +1,288 @@
//
// InterlockedTest.cs - NUnit Test Cases for System.Threading.Interlocked
//
// Author:
// Luca Barbieri (luca.barbieri@gmail.com)
//
// (C) 2004 Luca Barbieri
//
using NUnit.Framework;
using System;
using System.Threading;
namespace MonoTests.System.Threading
{
[TestFixture]
public class InterlockedTest
{
int int32;
long int64;
float flt;
double dbl;
object obj;
IntPtr iptr;
const int int32_1 = 0x12490082;
const int int32_2 = 0x24981071;
const int int32_3 = 0x36078912;
const long int64_1 = 0x1412803412472901L;
const long int64_2 = 0x2470232089701124L;
const long int64_3 = 0x3056432945919433L;
const float flt_1 = 141287.109874f;
const float flt_2 = 234108.324113f;
const float flt_3 = 342419.752395f;
const double dbl_1 = 141287.109874;
const double dbl_2 = 234108.324113;
const double dbl_3 = 342419.752395;
readonly object obj_1 = "obj_1";
readonly object obj_2 = "obj_2";
readonly object obj_3 = "obj_3";
#if !TARGET_JVM // No support for exchanging two IntPtrs
readonly IntPtr iptr_1 = (IntPtr)int32_1;
readonly IntPtr iptr_2 = (IntPtr)int32_2;
readonly IntPtr iptr_3 = (IntPtr)int32_3;
#endif // TARGET_JVM
[Test]
public void TestExchange_Int32 ()
{
int32 = int32_1;
Assert.AreEqual(int32_1, Interlocked.Exchange(ref int32, int32_2));
Assert.AreEqual(int32_2, int32);
}
[Test]
public void TestExchange_Flt ()
{
flt = flt_1;
Assert.AreEqual(flt_1, Interlocked.Exchange(ref flt, flt_2));
Assert.AreEqual(flt_2, flt);
}
[Test]
public void TestExchange_Obj ()
{
obj = obj_1;
Assert.AreEqual(obj_1, Interlocked.Exchange(ref obj, obj_2));
Assert.AreEqual(obj_2, obj);
}
#if NET_2_0
[Test]
public void TestExchange_Int64 ()
{
int64 = int64_1;
Assert.AreEqual(int64_1, Interlocked.Exchange(ref int64, int64_2));
Assert.AreEqual(int64_2, int64);
}
[Test]
public void TestExchange_Dbl ()
{
dbl = dbl_1;
Assert.AreEqual(dbl_1, Interlocked.Exchange(ref dbl, dbl_2));
Assert.AreEqual(dbl_2, dbl);
}
#if !TARGET_JVM // No support for exchanging two IntPtrs
[Test]
public void TestExchange_Iptr ()
{
iptr = iptr_1;
Assert.AreEqual(iptr_1, Interlocked.Exchange(ref iptr, iptr_2));
Assert.AreEqual(iptr_2, iptr);
}
#endif // TARGET_JVM
#endif
[Test]
public void TestCompareExchange_Int32 ()
{
int32 = int32_1;
Assert.AreEqual(int32_1, Interlocked.CompareExchange(ref int32, int32_2, int32_1));
Assert.AreEqual(int32_2, int32);
}
[Test]
public void TestCompareExchange_Flt ()
{
flt = flt_1;
Assert.AreEqual(flt_1, Interlocked.CompareExchange(ref flt, flt_2, flt_1));
Assert.AreEqual(flt_2, flt);
}
[Test]
public void TestCompareExchange_Obj ()
{
obj = obj_1;
Assert.AreEqual(obj_1, Interlocked.CompareExchange(ref obj, obj_2, obj_1));
Assert.AreEqual(obj_2, obj);
}
#if NET_2_0
[Test]
public void TestCompareExchange_Int64 ()
{
int64 = int64_1;
Assert.AreEqual(int64_1, Interlocked.CompareExchange(ref int64, int64_2, int64_1));
Assert.AreEqual(int64_2, int64);
}
[Test]
public void TestCompareExchange_Dbl ()
{
dbl = dbl_1;
Assert.AreEqual(dbl_1, Interlocked.CompareExchange(ref dbl, dbl_2, dbl_1));
Assert.AreEqual(dbl_2, dbl);
}
#if !TARGET_JVM // No support for compare exchanging two IntPtrs
[Test]
public void TestCompareExchange_Iptr ()
{
iptr = iptr_1;
Assert.AreEqual(iptr_1, Interlocked.CompareExchange(ref iptr, iptr_2, iptr_1));
Assert.AreEqual(iptr_2, iptr);
}
#endif // TARGET_JVM
#endif
[Test]
public void TestCompareExchange_Failed_Int32 ()
{
int32 = int32_1;
Assert.AreEqual(int32_1, Interlocked.CompareExchange(ref int32, int32_2, int32_3));
Assert.AreEqual(int32_1, int32);
}
[Test]
public void TestCompareExchange_Failed_Flt ()
{
flt = flt_1;
Assert.AreEqual(flt_1, Interlocked.CompareExchange(ref flt, flt_2, flt_3));
Assert.AreEqual(flt_1, flt);
}
[Test]
public void TestCompareExchange_Failed_Obj ()
{
obj = obj_1;
Assert.AreEqual(obj_1, Interlocked.CompareExchange(ref obj, obj_2, obj_3));
Assert.AreEqual(obj_1, obj);
}
#if NET_2_0
[Test]
public void TestCompareExchange_Failed_Int64 ()
{
int64 = int64_1;
Assert.AreEqual(int64_1, Interlocked.CompareExchange(ref int64, int64_2, int64_3));
Assert.AreEqual(int64_1, int64);
}
[Test]
public void TestCompareExchange_Failed_Dbl ()
{
dbl = dbl_1;
Assert.AreEqual(dbl_1, Interlocked.CompareExchange(ref dbl, dbl_2, dbl_3));
Assert.AreEqual(dbl_1, dbl);
}
#if !TARGET_JVM // No support for compare exchanging two IntPtrs
[Test]
public void TestCompareExchange_Failed_Iptr ()
{
iptr = iptr_1;
Assert.AreEqual(iptr_1, Interlocked.CompareExchange(ref iptr, iptr_2, iptr_3));
Assert.AreEqual(iptr_1, iptr);
}
#endif // TARGET_JVM
#endif
[Test]
public void TestIncrement_Int32 ()
{
int32 = int32_1;
Assert.AreEqual(int32_1 + 1, Interlocked.Increment(ref int32));
Assert.AreEqual(int32_1 + 1, int32);
}
[Test]
public void TestIncrement_Int64 ()
{
int64 = int64_1;
Assert.AreEqual(int64_1 + 1, Interlocked.Increment(ref int64), "func");
Assert.AreEqual(int64_1 + 1, int64, "value");
}
[Test]
public void TestDecrement_Int32 ()
{
int32 = int32_1;
Assert.AreEqual(int32_1 - 1, Interlocked.Decrement(ref int32));
Assert.AreEqual(int32_1 - 1, int32);
}
[Test]
public void TestDecrement_Int64 ()
{
int64 = int64_1;
Assert.AreEqual(int64_1 - 1, Interlocked.Decrement(ref int64));
Assert.AreEqual(int64_1 - 1, int64);
}
#if NET_2_0
[Test]
public void TestAdd_Int32 ()
{
int32 = int32_1;
Assert.AreEqual(int32_1 + int32_2, Interlocked.Add(ref int32, int32_2));
Assert.AreEqual(int32_1 + int32_2, int32);
}
[Test]
public void TestAdd_Int64 ()
{
int64 = int64_1;
Assert.AreEqual(int64_1 + int64_2, Interlocked.Add(ref int64, int64_2));
Assert.AreEqual(int64_1 + int64_2, int64);
}
[Test]
public void TestRead_Int64()
{
int64 = int64_1;
Assert.AreEqual(int64_1, Interlocked.Read(ref int64));
Assert.AreEqual(int64_1, int64);
}
[Test]
public void CompareExchange_Generic ()
{
object a = null;
Assert.IsNull (Interlocked.CompareExchange<object> (ref a, a, a), "null,null,null");
object b = new object ();
Assert.IsNull (Interlocked.CompareExchange<object> (ref a, a, b), "null,non-null,non-null");
Assert.IsNull (Interlocked.CompareExchange<object> (ref a, b, a), "null,non-null,null");
Assert.AreSame (b, Interlocked.CompareExchange<object> (ref a, b, b), "null,null,non-null");
Assert.AreSame (b, Interlocked.CompareExchange<object> (ref b, a, a), "non-null,null,null");
Assert.AreSame (b, Interlocked.CompareExchange<object> (ref b, a, b), "non-null,null,non-null");
Assert.AreSame (b, Interlocked.CompareExchange<object> (ref b, b, a), "non-null,non-null,null");
Assert.AreSame (b, Interlocked.CompareExchange<object> (ref b, b, b), "non-null,non-null,non-null");
}
[Test]
public void Exchange_Generic ()
{
object a = null;
Assert.IsNull (Interlocked.Exchange<object> (ref a, a), "null,null");
object b = new object ();
Assert.IsNull (Interlocked.Exchange<object> (ref a, b), "null,non-null");
Assert.AreSame (b, Interlocked.Exchange<object> (ref b, a), "non-null,null");
Assert.AreSame (b, Interlocked.Exchange<object> (ref b, b), "non-null,non-null");
}
#endif
}
}

View File

@@ -0,0 +1,96 @@
//
// LazyInitializerTest.cs
//
// Authors:
// Marek Safar (marek.safar@gmail.com)
//
// Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#if NET_4_0
using System;
using System.Threading;
using NUnit.Framework;
namespace MonoTests.System.Threading
{
[TestFixture]
public class LazyInitializerTest
{
class C
{
public C ()
{
++Counter;
}
public int Counter { get; private set; }
}
[Test]
public void EnsureInitialized_Simple ()
{
C c = null;
c = LazyInitializer.EnsureInitialized (ref c);
Assert.IsNotNull (c, "#1");
Assert.AreEqual (1, c.Counter, "#2");
}
[Test]
public void EnsureInitialized_FactoryIsNull ()
{
C c = null;
try {
LazyInitializer.EnsureInitialized (ref c, () => (C) null);
Assert.Fail ();
} catch (InvalidOperationException) {
}
}
[Test]
public void EnsureInitialized_NullLock ()
{
C c = null;
bool init = false;
object sync_lock = null;
c = LazyInitializer.EnsureInitialized (ref c, ref init, ref sync_lock);
Assert.IsNotNull (c, "#1");
Assert.AreEqual (1, c.Counter, "#2");
Assert.IsTrue (init, "#3");
Assert.IsNotNull (sync_lock, "#4");
var old_lock = sync_lock;
var d = LazyInitializer.EnsureInitialized (ref c, ref init, ref sync_lock);
Assert.AreEqual (c, d, "#11");
Assert.AreEqual (1, c.Counter, "#12");
Assert.IsTrue (init, "#13");
Assert.AreEqual (old_lock, sync_lock, "#14");
}
}
}
#endif

View File

@@ -0,0 +1,309 @@
// ManualResetEventSlimTests.cs
//
// Authors:
// Marek Safar (marek.safar@gmail.com)
// Jeremie Laval (jeremie.laval@gmail.com)
//
// Copyright (c) 2008 Jérémie "Garuma" Laval
// Copyright (c) 2012 Xamarin, Inc (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//
#if NET_4_0
using System;
using System.Threading;
using NUnit.Framework;
using MonoTests.System.Threading.Tasks;
namespace MonoTests.System.Threading
{
[TestFixture]
public class ManualResetEventSlimTests
{
ManualResetEventSlim mre;
[SetUp]
public void Setup()
{
mre = new ManualResetEventSlim();
}
[Test]
public void Constructor_Defaults ()
{
Assert.IsFalse (mre.IsSet, "#1");
Assert.AreEqual (10, mre.SpinCount, "#2");
}
[Test]
public void Constructor_Invalid ()
{
try {
new ManualResetEventSlim (true, -1);
Assert.Fail ("#1");
} catch (ArgumentException) {
}
try {
new ManualResetEventSlim (true, 2048);
Assert.Fail ("#2");
} catch (ArgumentException) {
}
}
[Test]
public void IsSetTestCase()
{
Assert.IsFalse(mre.IsSet, "#1");
mre.Set();
Assert.IsTrue(mre.IsSet, "#2");
mre.Reset();
Assert.IsFalse(mre.IsSet, "#3");
}
[Test]
public void WaitTest()
{
int count = 0;
bool s = false;
ParallelTestHelper.ParallelStressTest(mre, delegate (ManualResetEventSlim m) {
if (Interlocked.Increment(ref count) % 2 == 0) {
Thread.Sleep(50);
for (int i = 0; i < 10; i++) {
if (i % 2 == 0)
m.Reset();
else
m.Set();
}
} else {
m.Wait();
s = true;
}
}, 2);
Assert.IsTrue(s, "#1");
Assert.IsTrue(mre.IsSet, "#2");
}
[Test]
public void Wait_SetConcurrent ()
{
for (int i = 0; i < 10000; ++i) {
var mre = new ManualResetEventSlim ();
bool b = true;
ThreadPool.QueueUserWorkItem (delegate {
mre.Set ();
});
ThreadPool.QueueUserWorkItem (delegate {
b &= mre.Wait (1000);
});
Assert.IsTrue (mre.Wait (1000), i.ToString ());
Assert.IsTrue (b, i.ToString ());
}
}
[Test]
public void Wait_DisposeWithCancel ()
{
var token = new CancellationTokenSource ();
ThreadPool.QueueUserWorkItem (delegate {
Thread.Sleep (10);
mre.Dispose ();
token.Cancel ();
});
try {
mre.Wait (10000, token.Token);
Assert.Fail ("#0");
} catch (OperationCanceledException e) {
}
}
[Test]
public void Wait_Expired ()
{
Assert.IsFalse (mre.Wait (10));
}
[Test, ExpectedException (typeof (ObjectDisposedException))]
public void WaitAfterDisposeTest ()
{
mre.Dispose ();
mre.Wait ();
}
[Test]
public void SetAfterDisposeTest ()
{
ParallelTestHelper.Repeat (delegate {
Exception disp = null, setting = null;
CountdownEvent evt = new CountdownEvent (2);
CountdownEvent evtFinish = new CountdownEvent (2);
ThreadPool.QueueUserWorkItem (delegate {
try {
evt.Signal ();
evt.Wait (1000);
mre.Dispose ();
} catch (Exception e) {
disp = e;
}
evtFinish.Signal ();
});
ThreadPool.QueueUserWorkItem (delegate {
try {
evt.Signal ();
evt.Wait (1000);
mre.Set ();
} catch (Exception e) {
setting = e;
}
evtFinish.Signal ();
});
bool bb = evtFinish.Wait (1000);
if (!bb)
Assert.AreEqual (true, evtFinish.IsSet);
Assert.IsTrue (bb, "#0");
Assert.IsNull (disp, "#1");
Assert.IsNull (setting, "#2");
evt.Dispose ();
evtFinish.Dispose ();
});
}
[Test]
public void WaitHandle_Initialized ()
{
var mre = new ManualResetEventSlim (true);
Assert.IsTrue (mre.WaitHandle.WaitOne (0), "#1");
mre.Reset ();
Assert.IsFalse (mre.WaitHandle.WaitOne (0), "#2");
Assert.AreEqual (mre.WaitHandle, mre.WaitHandle, "#3");
}
[Test]
public void WaitHandle_NotInitialized ()
{
var mre = new ManualResetEventSlim (false);
Assert.IsFalse (mre.WaitHandle.WaitOne (0), "#1");
mre.Set ();
Assert.IsTrue (mre.WaitHandle.WaitOne (0), "#2");
}
[Test]
public void WaitHandleConsistencyTest ()
{
var mre = new ManualResetEventSlim ();
mre.WaitHandle.WaitOne (0);
for (int i = 0; i < 10000; i++) {
int count = 2;
SpinWait wait = new SpinWait ();
ThreadPool.QueueUserWorkItem (_ => { mre.Set (); Interlocked.Decrement (ref count); });
ThreadPool.QueueUserWorkItem (_ => { mre.Reset (); Interlocked.Decrement (ref count); });
while (count > 0)
wait.SpinOnce ();
Assert.AreEqual (mre.IsSet, mre.WaitHandle.WaitOne (0));
}
}
[Test]
public void WaitWithCancellationTokenAndNotImmediateSetTest ()
{
var mres = new ManualResetEventSlim ();
var cts = new CancellationTokenSource ();
ThreadPool.QueueUserWorkItem(x => { Thread.Sleep (1000); mres.Set (); });
Assert.IsTrue (mres.Wait (TimeSpan.FromSeconds (10), cts.Token), "Wait returned false despite event was set.");
}
[Test]
public void WaitWithCancellationTokenAndCancel ()
{
var mres = new ManualResetEventSlim ();
var cts = new CancellationTokenSource ();
ThreadPool.QueueUserWorkItem(x => { Thread.Sleep (1000); cts.Cancel (); });
try {
mres.Wait (TimeSpan.FromSeconds (10), cts.Token);
Assert.Fail ("Wait did not throw an exception despite cancellation token was cancelled.");
} catch (OperationCanceledException) {
}
}
[Test]
public void WaitWithCancellationTokenAndTimeout ()
{
var mres = new ManualResetEventSlim ();
var cts = new CancellationTokenSource ();
Assert.IsFalse (mres.Wait (TimeSpan.FromSeconds (1), cts.Token), "Wait returned true despite timeout.");
}
[Test]
public void Dispose ()
{
var mre = new ManualResetEventSlim (false);
mre.Dispose ();
Assert.IsFalse (mre.IsSet, "#0a");
try {
mre.Reset ();
Assert.Fail ("#1");
} catch (ObjectDisposedException) {
}
mre.Set ();
try {
mre.Wait (0);
Assert.Fail ("#3");
} catch (ObjectDisposedException) {
}
try {
var v = mre.WaitHandle;
Assert.Fail ("#4");
} catch (ObjectDisposedException) {
}
}
[Test]
public void Dispose_Double ()
{
var mre = new ManualResetEventSlim ();
mre.Dispose ();
mre.Dispose ();
}
}
}
#endif

View File

@@ -0,0 +1,340 @@
//
// MonitorTest.cs - NUnit test cases for System.Threading.Monitor
//
// Authors:
// Gonzalo Paniagua Javier (gonzalo@ximian.com)
// Sebastien Pouliot (sebastien@ximian.com)
//
// Copyright (C) 2005, 2009 Novell, Inc (http://www.novell.com)
//
using NUnit.Framework;
using System;
using System.Threading;
namespace MonoTests.System.Threading {
[TestFixture]
public class MonitorTest {
TimeSpan Infinite = new TimeSpan (-10000); // -10000 ticks == -1 ms
TimeSpan SmallNegative = new TimeSpan (-2); // between 0 and -1.0 (infinite) ms
TimeSpan Negative = new TimeSpan (-20000); // really negative
TimeSpan MaxValue = TimeSpan.FromMilliseconds ((long) Int32.MaxValue);
TimeSpan TooLarge = TimeSpan.FromMilliseconds ((long) Int32.MaxValue + 1);
[Test]
[ExpectedException (typeof (SynchronizationLockException))]
[Category ("NotWorking")] // test fails under MS FX 2.0 - maybe that worked on 1.x ?
public void ExitNoEnter ()
{
object o = new object ();
Monitor.Exit (o);
}
[Test]
[ExpectedException (typeof (SynchronizationLockException))]
[Category ("NotWorking")] // test fails under MS FX 2.0 - maybe that worked on 1.x ?
public void OneEnterSeveralExits ()
{
object o = new object ();
Monitor.Enter (o);
Monitor.Exit (o);
// fails here
Monitor.Exit (o);
Monitor.Exit (o);
Monitor.Exit (o);
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void Enter_Null ()
{
Monitor.Enter (null);
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void Exit_Null ()
{
Monitor.Exit (null);
}
[Test]
public void Enter_Exit ()
{
object o = new object ();
Monitor.Enter (o);
try {
Assert.IsNotNull (o);
}
finally {
Monitor.Exit (o);
}
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void Pulse_Null ()
{
Monitor.Pulse (null);
}
[Test]
[ExpectedException (typeof (SynchronizationLockException))]
public void Pulse_Unlocked ()
{
object o = new object ();
Monitor.Pulse (o);
}
[Test]
public void Pulse ()
{
object o = new object ();
lock (o) {
Monitor.Pulse (o);
}
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void PulseAll_Null ()
{
Monitor.PulseAll (null);
}
[Test]
[ExpectedException (typeof (SynchronizationLockException))]
public void PulseAll_Unlocked ()
{
object o = new object ();
Monitor.PulseAll (o);
}
[Test]
public void PulseAll ()
{
object o = new object ();
lock (o) {
Monitor.PulseAll (o);
}
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void TryEnter_Null ()
{
Monitor.TryEnter (null);
}
[Test]
public void TryEnter ()
{
object o = new object ();
Assert.IsTrue (Monitor.TryEnter (o), "TryEnter");
Assert.IsTrue (Monitor.TryEnter (o), "TryEnter-2");
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void TryEnter_Null_Int ()
{
Monitor.TryEnter (null, Timeout.Infinite);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void TryEnter_Int_Negative ()
{
object o = new object ();
Monitor.TryEnter (o, -2);
}
[Test]
public void TryEnter_Int ()
{
object o = new object ();
Assert.IsTrue (Monitor.TryEnter (o, 1), "TryEnter");
Assert.IsTrue (Monitor.TryEnter (o, 2), "TryEnter-2");
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void TryEnter_Null_TimeSpan ()
{
Monitor.TryEnter (null, Timeout.Infinite);
}
[Test]
[ExpectedException (typeof (ArgumentOutOfRangeException))]
public void TryEnter_TimeSpan_Negative ()
{
object o = new object ();
Monitor.TryEnter (o, Negative);
}
[Test]
[ExpectedException (typeof (ArgumentOutOfRangeException))]
public void TryEnter_TimeSpan_TooLarge ()
{
object o = new object ();
Monitor.TryEnter (o, TooLarge);
}
[Test]
[ExpectedException (typeof (ArgumentOutOfRangeException))]
public void TryEnter_Null_TimeSpan_TooLarge ()
{
// exception ordering test
Monitor.TryEnter (null, TooLarge);
}
[Test]
public void TryEnter_TimeSpan ()
{
object o = new object ();
Assert.IsTrue (Monitor.TryEnter (o, Infinite), "TryEnter");
Assert.IsTrue (Monitor.TryEnter (o, SmallNegative), "TryEnter-2");
Assert.IsTrue (Monitor.TryEnter (o, MaxValue), "TryEnter-3");
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void Wait_Null ()
{
Monitor.Wait (null);
}
[Test]
[ExpectedException (typeof (SynchronizationLockException))]
public void Wait_Unlocked ()
{
object o = new object ();
Assert.IsTrue (Monitor.Wait (o), "Wait");
}
// [Test] that would be Infinite
public void Wait ()
{
object o = new object ();
lock (o) {
Assert.IsFalse (Monitor.Wait (o), "Wait");
}
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void Wait_Null_Int ()
{
Monitor.Wait (null, Timeout.Infinite);
}
[Test]
[ExpectedException (typeof (ArgumentOutOfRangeException))]
public void Wait_Int_Negative ()
{
object o = new object ();
Monitor.Wait (o, -2);
}
[Test]
[ExpectedException (typeof (SynchronizationLockException))]
public void Wait_Int_Unlocked ()
{
object o = new object ();
Assert.IsTrue (Monitor.Wait (o, 1), "Wait");
}
[Test]
public void Wait_Int ()
{
object o = new object ();
lock (o) {
Assert.IsFalse (Monitor.Wait (o, 1), "Wait");
}
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void Wait_Null_TimeSpan ()
{
Monitor.Wait (null, Timeout.Infinite);
}
[Test]
[ExpectedException (typeof (ArgumentOutOfRangeException))]
public void Wait_TimeSpan_Negative ()
{
object o = new object ();
Monitor.Wait (o, Negative);
}
[Test]
[ExpectedException (typeof (ArgumentOutOfRangeException))]
public void Wait_TimeSpan_TooLarge ()
{
object o = new object ();
Monitor.Wait (o, TooLarge);
}
[Test]
[ExpectedException (typeof (ArgumentOutOfRangeException))]
public void Wait_Null_TimeSpan_TooLarge ()
{
// exception ordering test
Monitor.Wait (null, TooLarge);
}
[Test]
[ExpectedException (typeof (SynchronizationLockException))]
public void Wait_TimeSpan_Unlocked ()
{
object o = new object ();
Assert.IsTrue (Monitor.Wait (o, Infinite), "Wait");
}
[Test]
public void Wait_TimeSpan ()
{
object o = new object ();
lock (o) {
Assert.IsFalse (Monitor.Wait (o, SmallNegative), "Wait");
}
}
#if NET_4_0
[Test]
public void Enter_bool ()
{
object o = new object ();
bool taken = false;
Monitor.Enter (o, ref taken);
Assert.IsTrue (taken, "Monitor.Enter (obj, ref taken)");
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void Enter_bool_argcheck ()
{
object o = new object ();
bool taken = true;
Monitor.Enter (o, ref taken);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void Enter_bool_argcheck_fastpath ()
{
object o = new object ();
bool taken = false;
Monitor.Enter (o, ref taken);
taken = true;
Monitor.Enter (o, ref taken);
}
#endif
}
}

View File

@@ -0,0 +1,97 @@
//
// MutexCas.cs - CAS unit tests for System.Threading.Mutex
//
// Author:
// Sebastien Pouliot <sebastien@ximian.com>
//
// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using NUnit.Framework;
using System;
using System.Reflection;
using System.Security;
using System.Security.Permissions;
using System.Threading;
namespace MonoCasTests.System.Threading {
[TestFixture]
[Category ("CAS")]
public class MutexCas {
[SetUp]
public void SetUp ()
{
if (!SecurityManager.SecurityEnabled)
Assert.Ignore ("SecurityManager.SecurityEnabled is OFF");
}
// Partial Trust Tests - i.e. call "normal" unit with reduced privileges
[Test]
[PermissionSet (SecurityAction.Deny, Unrestricted = true)]
public void PartialTrust_DenyUnrestricted_Success ()
{
MonoTests.System.Threading.MutexTest mt = new MonoTests.System.Threading.MutexTest ();
// call the few working unit tests
mt.TestCtor1 ();
mt.TestHandle ();
}
// we use reflection to call Mutex as it's named constructors are protected by
// a LinkDemand (which will be converted into full demand, i.e. a stack walk)
// when reflection is used (i.e. it gets testable).
[Test]
[SecurityPermission (SecurityAction.Deny, UnmanagedCode = true)]
[ExpectedException (typeof (SecurityException))]
public void Ctor_BoolString ()
{
Type[] parameters = new Type [2] { typeof (bool), typeof (string) };
ConstructorInfo ci = typeof (Mutex).GetConstructor (parameters);
Assert.IsNotNull (ci, "ctor(bool,string)");
ci.Invoke (new object [2] { false, String.Empty });
}
[Test]
[SecurityPermission (SecurityAction.Deny, UnmanagedCode = true)]
[ExpectedException (typeof (SecurityException))]
public void Ctor_BoolStringOutBool ()
{
ConstructorInfo ci = null;
// I don't know an easier way to deal with "out bool"
ConstructorInfo[] cis = typeof (Mutex).GetConstructors ();
for (int i=0; i < cis.Length; i++) {
ParameterInfo[] pis = cis [i].GetParameters ();
if (pis.Length == 3) {
ci = cis [i];
break;
}
}
Assert.IsNotNull (ci, "ctor(bool,string,out bool)");
// not sure the invoke would work - but it's enough to trigger the security check
ci.Invoke (new object [3] { false, String.Empty, false });
}
}
}

View File

@@ -0,0 +1,181 @@
// MutexTest.cs - NUnit Test Cases for System.Threading.Mutex
//
// Eduardo Garcia Cebollero <kiwnix@yahoo.es>
//
// (C) Eduardo Garcia Cebollero
//
using System;
using System.Threading;
using NUnit.Framework;
namespace MonoTests.System.Threading
{
[TestFixture]
public class MutexTest
{
//Auxiliary Classes (Future Threads)
private class ConcClass
{
public int id;
public Mutex mut;
public ConcClass(int id,Mutex mut)
{
this.id = id;
this.mut = mut;
}
public void Wait()
{
mut.WaitOne();
}
public void Signal()
{
mut.ReleaseMutex();
}
}
private class ConcClassLoop: ConcClass
{
public int marker;
public ConcClassLoop(int id,Mutex mut) :
base(id,mut)
{
this.marker = 0;
}
public void WithoutWait()
{
this.marker = this.id;
this.Signal();
}
public void Loop()
{
while (this.marker<100)
{
this.Wait();
this.marker++;
this.Signal();
}
}
public void WaitAndForget()
{
this.Wait();
this.marker = id;
}
public void WaitAndWait()
{
mut.WaitOne();
this.marker = this.id;
mut.WaitOne();
this.marker = this.id+1;
}
}
[Test]
public void TestCtor1()
{
Mutex Sem = new Mutex();
}
// These tests produce mutex release errors
/**
[Test]
public void TestCtorDefaultValue()
{
Mutex Sem = new Mutex();
ConcClassLoop class1 = new ConcClassLoop(1,Sem);
Thread thread1 = new Thread(new ThreadStart(class1.WithoutWait));
thread1.Start();
while(thread1.IsAlive);
Assert.AreEqual(class1.id,class1.marker);
}
[Test]
public void TestCtorCtor2()
{
Mutex Sem = new Mutex(false);
ConcClassLoop class1 = new ConcClassLoop(1,Sem);
Thread thread1 = new Thread(new ThreadStart(class1.WithoutWait));
thread1.Start();
while(thread1.IsAlive);
Assert.AreEqual(class1.id,class1.marker);
}
[Test]
public void TestCtorCtor3()
{
Mutex Sem = new Mutex(true);
ConcClassLoop class1 = new ConcClassLoop(1,Sem);
Thread thread1 = new Thread(new ThreadStart(class1.WithoutWait));
thread1.Start();
while(thread1.IsAlive);
Assert.AreEqual(class1.id,class1.marker);
}
*/
[Test]
public void TestWaitAndSignal1()
{
Mutex Sem = new Mutex (false);
ConcClassLoop class1 = new ConcClassLoop (1, Sem);
Thread thread1 = new Thread (new ThreadStart (class1.Loop));
try {
thread1.Start ();
TestUtil.WaitForNotAlive (thread1, "");
Assert.AreEqual (100, class1.marker);
} finally {
thread1.Abort ();
}
}
[Test]
public void TestWaitAndFoget1()
{
Mutex Sem = new Mutex(false);
ConcClassLoop class1 = new ConcClassLoop(1,Sem);
ConcClassLoop class2 = new ConcClassLoop(2,Sem);
Thread thread1 = new Thread(new ThreadStart(class1.WaitAndForget));
Thread thread2 = new Thread(new ThreadStart(class2.WaitAndForget));
try {
thread1.Start();
TestUtil.WaitForNotAlive (thread1, "t1");
thread2.Start();
TestUtil.WaitForNotAlive (thread2, "t2");
Assert.AreEqual (class2.id, class2.marker);
} finally {
thread1.Abort ();
thread2.Abort ();
}
}
[Test]
[Category("TargetJvmNotSupported")] // IntPtr native handles are not supported for TARGET_JVM.
public void TestHandle()
{
Mutex Sem = new Mutex();
IntPtr Handle = Sem.Handle;
}
[Test] // bug #79358
public void DoubleRelease ()
{
Mutex mutex = new Mutex ();
mutex.WaitOne ();
mutex.ReleaseMutex ();
try {
mutex.ReleaseMutex ();
Assert.Fail ("#1");
} catch (ApplicationException ex) {
Assert.AreEqual (typeof (ApplicationException), ex.GetType (), "#2");
}
}
}
}

View File

@@ -0,0 +1,467 @@
//
// ReaderWriterLockTest.cs - NUnit Test Cases for System.Threading.ReaderWriterLock
//
// Author:
// Lluis Sanchez Gual (lluis@ximian.com)
//
// (C) 2004 Novell, Inc (http://www.novell.com)
//
using NUnit.Framework;
using System;
using System.Threading;
namespace MonoTests.System.Threading
{
[TestFixture]
public class ReaderWriterLockTest
{
ReaderWriterLock rwlock;
class ThreadRunner
{
public ThreadStart SecondaryThread;
public Exception ResultException;
public Thread RunningThread;
public void Run ()
{
try
{
SecondaryThread();
}
catch (Exception ex)
{
ResultException = ex;
}
}
public void Join ()
{
RunningThread.Join (5000);
if (ResultException != null) throw ResultException;
}
}
void RunThread (ThreadStart ts)
{
ThreadRunner tr = StartThread (ts);
tr.Join ();
}
ThreadRunner StartThread (ThreadStart ts)
{
ThreadRunner tr = new ThreadRunner();
tr.SecondaryThread = ts;
Thread t = new Thread (new ThreadStart (tr.Run));
tr.RunningThread = t;
t.Start ();
return tr;
}
[Test]
public void TestIsReaderLockHeld ()
{
rwlock = new ReaderWriterLock ();
Assert.IsTrue (!rwlock.IsReaderLockHeld, "#1");
rwlock.AcquireReaderLock (500);
Assert.IsTrue (rwlock.IsReaderLockHeld, "#1");
RunThread (new ThreadStart (IsReaderLockHeld_2));
rwlock.ReleaseReaderLock ();
}
private void IsReaderLockHeld_2 ()
{
Assert.IsTrue (!rwlock.IsReaderLockHeld);
}
[Test]
public void TestIsWriterLockHeld ()
{
rwlock = new ReaderWriterLock ();
Assert.IsTrue (!rwlock.IsWriterLockHeld, "#1");
rwlock.AcquireWriterLock (500);
Assert.IsTrue (rwlock.IsWriterLockHeld, "#2");
RunThread (new ThreadStart (IsWriterLockHeld_2));
rwlock.ReleaseWriterLock ();
}
private void IsWriterLockHeld_2 ()
{
Assert.IsTrue (!rwlock.IsWriterLockHeld);
}
[Test]
public void TestAcquireLocks ()
{
rwlock = new ReaderWriterLock ();
rwlock.AcquireReaderLock (500);
rwlock.AcquireReaderLock (500);
rwlock.ReleaseReaderLock ();
Assert.IsTrue (rwlock.IsReaderLockHeld, "#1");
RunThread (new ThreadStart (AcquireLock_readerWorks));
Assert.IsTrue (rwlock.IsReaderLockHeld);
RunThread (new ThreadStart (AcquireLock_writerFails));
rwlock.ReleaseReaderLock ();
Assert.IsTrue (!rwlock.IsReaderLockHeld);
RunThread (new ThreadStart (AcquireLock_writerWorks));
rwlock.AcquireWriterLock (200);
RunThread (new ThreadStart (AcquireLock_writerFails));
RunThread (new ThreadStart (AcquireLock_readerFails));
rwlock.ReleaseWriterLock ();
}
void AcquireLock_readerWorks ()
{
rwlock.AcquireReaderLock (200);
rwlock.AcquireReaderLock (200);
rwlock.ReleaseReaderLock ();
Assert.IsTrue (rwlock.IsReaderLockHeld);
rwlock.ReleaseReaderLock ();
Assert.IsTrue (!rwlock.IsReaderLockHeld);
}
void AcquireLock_writerFails ()
{
try
{
rwlock.AcquireWriterLock (200);
rwlock.ReleaseWriterLock ();
throw new Exception ("Should not get writer lock");
}
catch (Exception)
{
}
}
void AcquireLock_writerWorks ()
{
rwlock.AcquireWriterLock (200);
rwlock.ReleaseWriterLock ();
}
void AcquireLock_readerFails ()
{
try
{
rwlock.AcquireReaderLock (200);
rwlock.ReleaseReaderLock ();
throw new Exception ("Should not get reader lock");
}
catch (Exception)
{
}
}
[Test]
public void TestReleaseRestoreReaderLock ()
{
rwlock = new ReaderWriterLock ();
rwlock.AcquireReaderLock (500);
rwlock.AcquireReaderLock (500);
Assert.IsTrue (rwlock.IsReaderLockHeld);
LockCookie co = rwlock.ReleaseLock ();
RunThread (new ThreadStart (AcquireLock_writerWorks));
rwlock.RestoreLock (ref co);
RunThread (new ThreadStart (AcquireLock_writerFails));
rwlock.ReleaseReaderLock ();
Assert.IsTrue (rwlock.IsReaderLockHeld);
rwlock.ReleaseReaderLock ();
Assert.IsTrue (!rwlock.IsReaderLockHeld);
}
[Test]
public void TestReleaseRestoreWriterLock ()
{
rwlock = new ReaderWriterLock ();
rwlock.AcquireWriterLock (500);
rwlock.AcquireWriterLock (500);
Assert.IsTrue (rwlock.IsWriterLockHeld);
LockCookie co = rwlock.ReleaseLock ();
RunThread (new ThreadStart (AcquireLock_readerWorks));
rwlock.RestoreLock (ref co);
RunThread (new ThreadStart (AcquireLock_readerFails));
rwlock.ReleaseWriterLock ();
Assert.IsTrue (rwlock.IsWriterLockHeld);
rwlock.ReleaseWriterLock ();
Assert.IsTrue (!rwlock.IsWriterLockHeld);
}
[Test]
public void TestUpgradeDowngradeLock ()
{
rwlock = new ReaderWriterLock ();
rwlock.AcquireReaderLock (200);
rwlock.AcquireReaderLock (200);
LockCookie co = rwlock.UpgradeToWriterLock (200);
Assert.IsTrue (!rwlock.IsReaderLockHeld);
Assert.IsTrue (rwlock.IsWriterLockHeld);
RunThread (new ThreadStart (AcquireLock_writerFails));
rwlock.DowngradeFromWriterLock (ref co);
Assert.IsTrue (rwlock.IsReaderLockHeld);
Assert.IsTrue (!rwlock.IsWriterLockHeld);
RunThread (new ThreadStart (AcquireLock_readerWorks));
rwlock.ReleaseReaderLock ();
Assert.IsTrue (rwlock.IsReaderLockHeld);
rwlock.ReleaseReaderLock ();
Assert.IsTrue (!rwlock.IsReaderLockHeld);
}
[Test]
public void TestReaderInsideWriter ()
{
// Reader acquires and releases work like the writer equivalent
rwlock = new ReaderWriterLock ();
rwlock.AcquireWriterLock (-1);
rwlock.AcquireReaderLock (-1);
Assert.IsTrue (!rwlock.IsReaderLockHeld);
Assert.IsTrue (rwlock.IsWriterLockHeld);
rwlock.AcquireReaderLock (-1);
Assert.IsTrue (!rwlock.IsReaderLockHeld);
Assert.IsTrue (rwlock.IsWriterLockHeld);
rwlock.ReleaseWriterLock ();
Assert.IsTrue (!rwlock.IsReaderLockHeld);
Assert.IsTrue (rwlock.IsWriterLockHeld);
rwlock.ReleaseReaderLock ();
Assert.IsTrue (!rwlock.IsReaderLockHeld);
Assert.IsTrue (rwlock.IsWriterLockHeld);
rwlock.ReleaseReaderLock ();
Assert.IsTrue (!rwlock.IsReaderLockHeld);
Assert.IsTrue (!rwlock.IsWriterLockHeld);
}
[Test]
public void TestReaderMustWaitWriter ()
{
// A thread cannot get the reader lock if there are other threads
// waiting for the writer lock.
rwlock = new ReaderWriterLock ();
rwlock.AcquireWriterLock (200);
ThreadRunner tr = StartThread (new ThreadStart (ReaderMustWaitWriter_2));
Thread.Sleep (200);
RunThread (new ThreadStart (AcquireLock_readerFails));
rwlock.ReleaseReaderLock ();
tr.Join ();
}
void ReaderMustWaitWriter_2 ()
{
rwlock.AcquireWriterLock (2000);
rwlock.ReleaseWriterLock ();
}
[Test]
public void TestBug_55911 ()
{
rwlock = new ReaderWriterLock ();
rwlock.AcquireReaderLock (Timeout.Infinite);
try {
LockCookie lc = rwlock.UpgradeToWriterLock (Timeout.Infinite);
}
finally { rwlock.ReleaseReaderLock(); }
rwlock.AcquireReaderLock (Timeout.Infinite);
try {
LockCookie lc = rwlock.UpgradeToWriterLock (Timeout.Infinite);
}
finally { rwlock.ReleaseReaderLock(); }
}
[Test]
public void TestBug_55909 ()
{
rwlock = new ReaderWriterLock ();
ThreadRunner tr = StartThread (new ThreadStart(Bug_55909_Thread2));
Thread.Sleep (200);
rwlock.AcquireReaderLock (Timeout.Infinite);
try {
LockCookie lc = rwlock.UpgradeToWriterLock (Timeout.Infinite);
Thread.Sleep (500);
}
finally { rwlock.ReleaseReaderLock(); }
tr.Join ();
}
public void Bug_55909_Thread2 ()
{
rwlock.AcquireReaderLock(Timeout.Infinite);
try {
Thread.Sleep (1000);
LockCookie lc = rwlock.UpgradeToWriterLock (Timeout.Infinite);
Thread.Sleep (500);
}
finally { rwlock.ReleaseReaderLock(); }
}
[Test]
public void TestBug_55909_bis ()
{
rwlock = new ReaderWriterLock ();
ThreadRunner tr1 = StartThread (new ThreadStart(Bug_55909_bis_ReaderWriter));
Thread.Sleep(100);
ThreadRunner tr2 = StartThread (new ThreadStart(Bug_55909_bis_Reader));
Thread.Sleep(100);
ThreadRunner tr3 = StartThread (new ThreadStart(Bug_55909_bis_Writer));
Thread.Sleep(100);
ThreadRunner tr4 = StartThread (new ThreadStart(Bug_55909_bis_Reader));
tr1.Join ();
tr2.Join ();
tr3.Join ();
tr4.Join ();
}
void Bug_55909_bis_Reader ()
{
rwlock.AcquireReaderLock(-1);
Thread.Sleep(2000);
rwlock.ReleaseReaderLock();
}
void Bug_55909_bis_ReaderWriter ()
{
rwlock.AcquireReaderLock(-1);
LockCookie lc = rwlock.UpgradeToWriterLock(-1);
Thread.Sleep(1000);
rwlock.DowngradeFromWriterLock(ref lc);
rwlock.ReleaseReaderLock();
}
void Bug_55909_bis_Writer ()
{
rwlock.AcquireWriterLock(-1);
rwlock.ReleaseWriterLock();
}
[Test]
public void TestBug_475124 ()
{
LockCookie lc1, lc2;
rwlock = new ReaderWriterLock ();
Assert.IsFalse (rwlock.IsReaderLockHeld, "A1");
Assert.IsFalse (rwlock.IsWriterLockHeld, "A2");
rwlock.AcquireReaderLock (Timeout.Infinite);
Assert.IsTrue (rwlock.IsReaderLockHeld, "B1");
Assert.IsFalse (rwlock.IsWriterLockHeld, "B2");
lc1 = rwlock.UpgradeToWriterLock (Timeout.Infinite);
Assert.IsFalse (rwlock.IsReaderLockHeld, "C1");
Assert.IsTrue (rwlock.IsWriterLockHeld, "C2");
rwlock.AcquireReaderLock (Timeout.Infinite);
Assert.IsFalse (rwlock.IsReaderLockHeld, "D1");
Assert.IsTrue (rwlock.IsWriterLockHeld, "D2");
lc2 = rwlock.UpgradeToWriterLock (Timeout.Infinite);
Assert.IsFalse (rwlock.IsReaderLockHeld, "E1");
Assert.IsTrue (rwlock.IsWriterLockHeld, "E2");
rwlock.DowngradeFromWriterLock (ref lc2);
Assert.IsFalse (rwlock.IsReaderLockHeld, "F1");
Assert.IsTrue (rwlock.IsWriterLockHeld, "F2");
rwlock.ReleaseReaderLock ();
Assert.IsFalse (rwlock.IsReaderLockHeld, "G1");
Assert.IsTrue (rwlock.IsWriterLockHeld, "G2");
rwlock.DowngradeFromWriterLock (ref lc1);
Assert.IsTrue (rwlock.IsReaderLockHeld, "H1");
Assert.IsFalse (rwlock.IsWriterLockHeld, "H2");
rwlock.ReleaseReaderLock ();
Assert.IsFalse (rwlock.IsReaderLockHeld, "I1");
Assert.IsFalse (rwlock.IsWriterLockHeld, "I2");
}
// this tests how downgrade works when multiple writer locks
// are acquired - as long as the LockCookie referes to an
// upgrade where there was already a writer lock, downgrade
// behaves like a non-blocking ReleaseWriterLock
[Test]
public void DowngradeTest ()
{
LockCookie lc1, lc2, lc3, lc4;
rwlock = new ReaderWriterLock ();
rwlock.AcquireReaderLock (Timeout.Infinite);
lc1 = rwlock.UpgradeToWriterLock (Timeout.Infinite);
rwlock.AcquireReaderLock (Timeout.Infinite);
lc2 = rwlock.UpgradeToWriterLock (Timeout.Infinite);
rwlock.AcquireReaderLock (Timeout.Infinite);
lc3 = rwlock.UpgradeToWriterLock (Timeout.Infinite);
rwlock.AcquireReaderLock (Timeout.Infinite);
lc4 = rwlock.UpgradeToWriterLock (Timeout.Infinite);
rwlock.DowngradeFromWriterLock (ref lc2);
Assert.IsFalse (rwlock.IsReaderLockHeld, "A1");
Assert.IsTrue (rwlock.IsWriterLockHeld, "A2");
rwlock.ReleaseReaderLock ();
Assert.IsFalse (rwlock.IsReaderLockHeld, "B1");
Assert.IsTrue (rwlock.IsWriterLockHeld, "B2");
rwlock.DowngradeFromWriterLock (ref lc4);
Assert.IsFalse (rwlock.IsReaderLockHeld, "C1");
Assert.IsTrue (rwlock.IsWriterLockHeld, "C2");
rwlock.ReleaseReaderLock ();
Assert.IsFalse (rwlock.IsReaderLockHeld, "D1");
Assert.IsTrue (rwlock.IsWriterLockHeld, "D2");
rwlock.DowngradeFromWriterLock (ref lc3);
Assert.IsFalse (rwlock.IsReaderLockHeld, "E1");
Assert.IsTrue (rwlock.IsWriterLockHeld, "E2");
rwlock.ReleaseReaderLock ();
Assert.IsFalse (rwlock.IsReaderLockHeld, "F1");
Assert.IsTrue (rwlock.IsWriterLockHeld, "F2");
rwlock.DowngradeFromWriterLock (ref lc1);
Assert.IsTrue (rwlock.IsReaderLockHeld, "G1");
Assert.IsFalse (rwlock.IsWriterLockHeld, "G2");
rwlock.ReleaseReaderLock ();
Assert.IsFalse (rwlock.IsReaderLockHeld, "H1");
Assert.IsFalse (rwlock.IsWriterLockHeld, "H2");
}
}
}

View File

@@ -0,0 +1,93 @@
#if NET_4_0
// SemaphoreSlimTests.cs
//
// Copyright (c) 2008 Jérémie "Garuma" Laval
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//
using System;
using System.Linq;
using System.Threading;
using MonoTests.System.Threading.Tasks;
using NUnit.Framework;
namespace MonoTests.System.Threading
{
[TestFixture]
public class SemaphoreSlimTests
{
SemaphoreSlim sem;
SemaphoreSlim semMax;
[SetUp]
public void Setup()
{
sem = new SemaphoreSlim(5);
semMax = new SemaphoreSlim(5, 5);
}
[Test]
public void CurrentCountMaxTestCase()
{
semMax.Wait();
semMax.Release(3);
Assert.AreEqual(5, semMax.CurrentCount);
}
[Test]
public void CurrentCountTestCase()
{
sem.Wait();
sem.Wait();
sem.Release();
Assert.AreEqual(4, sem.CurrentCount);
}
[Test]
public void WaitStressTest()
{
int count = -1;
bool[] array = new bool[7];
int worker = 0;
bool coherent = true;
ParallelTestHelper.ParallelStressTest (sem, delegate (SemaphoreSlim s) {
int index = Interlocked.Increment (ref count);
s.Wait ();
if (Interlocked.Increment (ref worker) > 5)
coherent = false;
Thread.Sleep (40);
Interlocked.Decrement (ref worker);
s.Release ();
array[index] = true;
}, 7);
bool result = array.Aggregate ((acc, e) => acc && e);
Assert.IsTrue (result, "#1");
Assert.AreEqual (5, sem.CurrentCount, "#2");
Assert.IsTrue (coherent, "#3");
}
}
}
#endif

View File

@@ -0,0 +1,156 @@
#if NET_4_0
//
// SpinLockTests.cs
//
// Author:
// Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
//
// Copyright (c) 2010 Jérémie "Garuma" Laval
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Threading;
using NUnit.Framework;
using MonoTests.System.Threading.Tasks;
namespace MonoTests.System.Threading
{
[TestFixture]
public class SpinLockTests
{
SpinLock sl;
[SetUp]
public void Setup ()
{
sl = new SpinLock (true);
}
[Test, ExpectedException (typeof (LockRecursionException))]
public void RecursionExceptionTest ()
{
sl = new SpinLock (true);
bool taken = false, taken2 = false;
sl.Enter (ref taken);
Assert.IsTrue (taken, "#1");
sl.Enter (ref taken2);
}
[Test]
public void SimpleEnterExitSchemeTest ()
{
bool taken = false;
for (int i = 0; i < 50000; i++) {
sl.Enter (ref taken);
Assert.IsTrue (taken, "#" + i.ToString ());
sl.Exit ();
taken = false;
}
}
[Test]
public void SemanticCorrectnessTest ()
{
sl = new SpinLock (false);
bool taken = false;
bool taken2 = false;
sl.Enter (ref taken);
Assert.IsTrue (taken, "#1");
sl.TryEnter (ref taken2);
Assert.IsFalse (taken2, "#2");
sl.Exit ();
sl.TryEnter (ref taken2);
Assert.IsTrue (taken2, "#3");
}
[Test, ExpectedException (typeof (ArgumentException))]
public void FirstTakenParameterTest ()
{
bool taken = true;
sl.Enter (ref taken);
}
[Test, ExpectedException (typeof (ArgumentException))]
public void SecondTakenParameterTest ()
{
bool taken = true;
sl.TryEnter (ref taken);
}
internal class SpinLockWrapper
{
public SpinLock Lock = new SpinLock (false);
}
[Test]
public void LockUnicityTest ()
{
ParallelTestHelper.Repeat (delegate {
int currentCount = 0;
bool fail = false;
SpinLockWrapper wrapper = new SpinLockWrapper ();
ParallelTestHelper.ParallelStressTest (wrapper, delegate {
bool taken = false;
wrapper.Lock.Enter (ref taken);
int current = currentCount++;
if (current != 0)
fail = true;
SpinWait sw = new SpinWait ();
for (int i = 0; i < 200; i++)
sw.SpinOnce ();
currentCount -= 1;
wrapper.Lock.Exit ();
}, 4);
Assert.IsFalse (fail);
}, 200);
}
[Test]
public void IsHeldByCurrentThreadTest ()
{
bool lockTaken = false;
sl.Enter (ref lockTaken);
Assert.IsTrue (lockTaken, "#1");
Assert.IsTrue (sl.IsHeldByCurrentThread, "#2");
lockTaken = false;
sl = new SpinLock (true);
sl.Enter (ref lockTaken);
Assert.IsTrue (lockTaken, "#3");
Assert.IsTrue (sl.IsHeldByCurrentThread, "#4");
}
}
}
#endif

View File

@@ -0,0 +1,142 @@
//
// ThreadCas.cs - CAS unit tests for System.Threading.Thread
//
// Author:
// Sebastien Pouliot <sebastien@ximian.com>
//
// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using NUnit.Framework;
using System;
using System.Globalization;
using System.Reflection;
using System.Security;
using System.Security.Permissions;
using System.Threading;
namespace MonoCasTests.System.Threading {
[TestFixture]
[Category ("CAS")]
public class ThreadCas {
private Type ThreadType;
[TestFixtureSetUp]
public void FixtureSetUp ()
{
ThreadType = typeof (Thread);
}
[SetUp]
public void SetUp ()
{
if (!SecurityManager.SecurityEnabled)
Assert.Ignore ("SecurityManager.SecurityEnabled is OFF");
}
// Partial Trust Tests - i.e. call "normal" unit with reduced privileges
[Test]
[PermissionSet (SecurityAction.Deny, Unrestricted = true)]
public void PartialTrust_DenyUnrestricted_Success ()
{
MonoTests.System.Threading.ThreadTest tt = new MonoTests.System.Threading.ThreadTest ();
tt.TestCtor1 ();
// most tests use Abort so there's not much to call
}
// test Demand by denying the caller of the required privileges
[Test]
[SecurityPermission (SecurityAction.Deny, ControlThread = true)]
[ExpectedException (typeof (SecurityException))]
public void Abort ()
{
Thread.CurrentThread.Abort ();
}
[Test]
[SecurityPermission (SecurityAction.Deny, ControlThread = true)]
[ExpectedException (typeof (SecurityException))]
public void Abort_Object ()
{
Thread.CurrentThread.Abort (new object [0]);
}
[Test]
[SecurityPermission (SecurityAction.Deny, ControlThread = true)]
[ExpectedException (typeof (SecurityException))]
public void CurrentCulture ()
{
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
}
[Test]
[SecurityPermission (SecurityAction.Deny, ControlThread = true)]
[ExpectedException (typeof (SecurityException))]
public void Interrupt ()
{
Thread.CurrentThread.Interrupt ();
}
[Test]
[SecurityPermission (SecurityAction.Deny, ControlThread = true)]
[ExpectedException (typeof (SecurityException))]
public void ResetAbort ()
{
Thread.ResetAbort ();
}
[Test]
[SecurityPermission (SecurityAction.Deny, ControlThread = true)]
[ExpectedException (typeof (SecurityException))]
public void Resume ()
{
Thread.CurrentThread.Resume ();
}
[Test]
[SecurityPermission (SecurityAction.Deny, ControlThread = true)]
[ExpectedException (typeof (SecurityException))]
public void Suspend ()
{
Thread.CurrentThread.Suspend ();
}
// we use reflection to call Mutex as it's named constructors are protected by
// a LinkDemand (which will be converted into full demand, i.e. a stack walk)
// when reflection is used (i.e. it gets testable).
[Test]
[SecurityPermission (SecurityAction.Deny, Infrastructure = true)]
[ExpectedException (typeof (SecurityException))]
public void CurrentContext ()
{
MethodInfo mi = ThreadType.GetProperty ("CurrentContext").GetGetMethod ();
Assert.IsNotNull (mi, "get_CurrentContext");
mi.Invoke (null, null);
}
}
}

Some files were not shown because too many files have changed in this diff Show More