2010-04-06 Jb Evain <jbevain@novell.com>
[mcs.git] / class / corlib / Test / System.Runtime.InteropServices / SafeHandleTest.cs
blobcc2488a647cd9a3f127a5a9491549966298c46ba
1 //
2 // System.Runtime.InteropServices.SafeHandle Test Cases
3 //
4 // Authors:
5 // Miguel de Icaza (miguel@novell.com)
6 //
7 // Copyright (C) 2004-2006 Novell, Inc (http://www.novell.com)
8 //
9 #if NET_2_0
10 using NUnit.Framework;
11 using System;
12 using System.Runtime.InteropServices;
13 using System.Security;
14 using Microsoft.Win32.SafeHandles;
16 namespace MonoTests.System.Runtime.InteropServices
18 [TestFixture]
19 public class SafeHandleTest
22 // This mimics SafeFileHandle, but does not actually own a handle
23 // We use this to test ownership and dispose exceptions.
25 public class FakeSafeHandle : SafeHandleZeroOrMinusOneIsInvalid
27 public bool released = false;
29 public FakeSafeHandle (): base (true)
33 public FakeSafeHandle (bool ownership) : base (ownership)
37 protected override bool ReleaseHandle ()
39 released = true;
40 return true;
44 [Test]
45 [ExpectedException (typeof (ObjectDisposedException))]
46 public void Dispose1 ()
48 FakeSafeHandle sf = new FakeSafeHandle ();
50 sf.DangerousRelease ();
51 sf.DangerousRelease ();
54 [Test]
55 [ExpectedException (typeof (ObjectDisposedException))]
56 public void Dispose2 ()
58 FakeSafeHandle sf = new FakeSafeHandle ();
60 sf.DangerousRelease ();
61 sf.Close ();
64 [Test]
65 [ExpectedException (typeof (ObjectDisposedException))]
66 public void Dispose3 ()
68 FakeSafeHandle sf = new FakeSafeHandle ();
70 sf.Close ();
71 sf.DangerousRelease ();
74 [Test]
75 public void NoReleaseUnowned ()
77 FakeSafeHandle sf = new FakeSafeHandle (false);
79 sf.Close ();
80 Assert.AreEqual (sf.released, false, "r1");
82 sf = new FakeSafeHandle (false);
83 sf.DangerousRelease ();
84 Assert.AreEqual (sf.released, false, "r2");
86 sf = new FakeSafeHandle (false);
87 ((IDisposable) sf).Dispose ();
88 Assert.AreEqual (sf.released, false, "r3");
92 // This test does a DangerousAddRef on a new instance
93 // of a custom user Safe Handle, and it just happens
94 // that the default value for the handle is an invalid
95 // handle.
97 // .NET does not throw an exception in this case, so
98 // we should not either
100 [Test]
101 public void DangerousAddRefOnNewInstance ()
103 var h = new IntPtrSafe ();
104 var success = false;
105 h.DangerousAddRef (ref success);
106 Assert.AreEqual (success, true, "daroni");
109 public class IntPtrSafe : SafeHandle {
110 public IntPtrSafe() : base(IntPtr.Zero, true)
114 protected override bool ReleaseHandle()
116 return true;
119 public IntPtr Handle { get; set; }
121 public override bool IsInvalid
123 get { return Handle == IntPtr.Zero; }
129 #endif