2 // System.Runtime.InteropServices.SafeHandle Test Cases
5 // Miguel de Icaza (miguel@novell.com)
7 // Copyright (C) 2004-2006 Novell, Inc (http://www.novell.com)
10 using NUnit
.Framework
;
12 using System
.Runtime
.InteropServices
;
13 using System
.Security
;
14 using Microsoft
.Win32
.SafeHandles
;
16 namespace MonoTests
.System
.Runtime
.InteropServices
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 ()
45 [ExpectedException (typeof (ObjectDisposedException
))]
46 public void Dispose1 ()
48 FakeSafeHandle sf
= new FakeSafeHandle ();
50 sf
.DangerousRelease ();
51 sf
.DangerousRelease ();
55 [ExpectedException (typeof (ObjectDisposedException
))]
56 public void Dispose2 ()
58 FakeSafeHandle sf
= new FakeSafeHandle ();
60 sf
.DangerousRelease ();
65 [ExpectedException (typeof (ObjectDisposedException
))]
66 public void Dispose3 ()
68 FakeSafeHandle sf
= new FakeSafeHandle ();
71 sf
.DangerousRelease ();
75 public void NoReleaseUnowned ()
77 FakeSafeHandle sf
= new FakeSafeHandle (false);
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
97 // .NET does not throw an exception in this case, so
98 // we should not either
101 public void DangerousAddRefOnNewInstance ()
103 var h
= new IntPtrSafe ();
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()
119 public IntPtr Handle { get; set; }
121 public override bool IsInvalid
123 get { return Handle == IntPtr.Zero; }