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

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,118 @@
//
// CookieCollectionTest.cs - NUnit Test Cases for System.Net.CookieCollection
//
// Authors:
// Lawrence Pit (loz@cable.a2000.nl)
// Martin Willemoes Hansen (mwh@sysrq.dk)
//
// (C) 2003 Martin Willemoes Hansen
//
using NUnit.Framework;
using System;
using System.Net;
using System.Collections;
namespace MonoTests.System.Net
{
[TestFixture]
public class CookieCollectionTest
{
CookieCollection col;
[SetUp]
public void GetReady ()
{
col = new CookieCollection ();
col.Add (new Cookie ("name1", "value1"));
col.Add (new Cookie ("name2", "value2", "path2"));
col.Add (new Cookie ("name3", "value3", "path3", "domain3"));
}
[Test]
public void Count ()
{
Assert.AreEqual (col.Count, 3, "#1");
}
[Test]
public void Indexer ()
{
Cookie c = null;
try {
c = col [-1];
Assert.Fail ("#1");
} catch (ArgumentOutOfRangeException) {
}
try {
c = col [col.Count];
Assert.Fail ("#2");
} catch (ArgumentOutOfRangeException) {
}
c = col ["name1"];
Assert.AreEqual (c.Name, "name1", "#3");
c = col ["NAME2"];
Assert.AreEqual (c.Name, "name2", "#4");
}
[Test]
public void Add ()
{
try {
Cookie c = null;
col.Add (c);
Assert.Fail ("#1");
} catch (ArgumentNullException) {
}
// in the microsoft implementation this will fail,
// so we'll have to fail to.
try {
col.Add (col);
Assert.Fail ("#2");
} catch (Exception) {
}
Assert.AreEqual (col.Count, 3, "#3");
col.Add (new Cookie("name1", "value1"));
Assert.AreEqual (col.Count, 3, "#4");
CookieCollection col2 = new CookieCollection();
Cookie c4 = new Cookie("name4", "value4");
Cookie c5 = new Cookie("name5", "value5");
col2.Add (c4);
col2.Add (c5);
col.Add (col2);
Assert.AreEqual (col.Count, 5, "#5");
Assert.AreEqual (col ["NAME4"], c4, "#6");
Assert.AreEqual (col [4], c5, "#7");
}
[Test]
public void CopyTo ()
{
Array a = Array.CreateInstance (typeof (Cookie), 3);
col.CopyTo (a, 0);
Assert.AreEqual (a.GetValue (0), col [0], "#1");
Assert.AreEqual (a.GetValue (1), col [1], "#2");
Assert.AreEqual (a.GetValue (2), col [2], "#3");
}
[Test]
public void Enumerator ()
{
IEnumerator enumerator = col.GetEnumerator ();
enumerator.MoveNext ();
Cookie c = (Cookie) enumerator.Current;
Assert.AreEqual (c, col [0], "#1");
col.Add (new Cookie ("name6", "value6"));
try {
enumerator.MoveNext ();
Assert.Fail ("#2");
} catch (InvalidOperationException) {
}
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,193 @@
using System;
using System.IO;
using System.Threading;
using System.Globalization;
using System.Net;
using System.Net.Sockets;
using NUnit.Framework;
namespace MonoTests.System.Net
{
[TestFixture]
public class CookieParserTest
{
public const string A = "Foo=Bar, expires=World; expires=Sat, 11-Oct-14 22:45:19 GMT, A=B";
public const string B = "A=B=C, expires=Sat, 99-Dec-01 01:00:00 XDT; Hello=World, Foo=Bar";
// Only the invariant culture is allowed.
public const string C = "Foo=Bar, expires=Montag, 21. Juni 2012 23:11:45";
// Only comma serves as separation character.
public const string D = "A=B, C=D; E=F, G=H";
public const string E = "A; C; expires=Tue, 25-Jun-19 00:51:34 GMT, E=F";
public const string F = "Foo = \" A, B\"C D, E=F";
CookieCollection DoRequest (string header)
{
HttpWebResponse res;
using (var listener = new Listener ("Set-Cookie: " + header)) {
var req = (HttpWebRequest)HttpWebRequest.Create (listener.URI);
req.CookieContainer = new CookieContainer ();
req.Method = "POST";
res = (HttpWebResponse)req.GetResponse ();
}
Assert.AreEqual (header, res.Headers.Get ("Set-Cookie"));
return res.Cookies;
}
void AssertCookie (Cookie cookie, string name, string value, long ticks)
{
AssertCookie (cookie, name, value);
if (ticks == 0)
Assert.AreEqual (0, cookie.Expires.Ticks);
else
Assert.AreEqual (ticks, cookie.Expires.ToUniversalTime ().Ticks);
}
void AssertCookie (Cookie cookie, string name, string value)
{
Assert.AreEqual (name, cookie.Name);
Assert.AreEqual (value, cookie.Value);
}
[Test]
public void TestDate ()
{
var d1 = "Sat, 11-Oct-14 22:45:19 GMT";
var d2 = "Tue, 25-Jun-19 00:51:34 GMT";
var format = "ddd, dd'-'MMM'-'yy HH':'mm':'ss 'GMT'";
var p1 = DateTime.ParseExact (d1, format, CultureInfo.InvariantCulture);
p1 = DateTime.SpecifyKind (p1, DateTimeKind.Utc);
Assert.AreEqual ("10/11/2014 22:45:19", p1.ToString ("G", CultureInfo.InvariantCulture));
Assert.AreEqual (p1.Ticks, p1.ToUniversalTime ().Ticks);
Assert.AreEqual (635486643190000000, p1.Ticks);
var p2 = DateTime.ParseExact (d2, format, CultureInfo.InvariantCulture);
p2 = DateTime.SpecifyKind (p2, DateTimeKind.Utc);
Assert.AreEqual ("06/25/2019 00:51:34", p2.ToString ("G", CultureInfo.InvariantCulture));
Assert.AreEqual (p2.Ticks, p2.ToUniversalTime ().Ticks);
Assert.AreEqual (636970206940000000, p2.Ticks);
}
[Test]
public void TestExpires ()
{
var cookies = DoRequest (A);
Assert.AreEqual (3, cookies.Count);
AssertCookie (cookies [0], "Foo", "Bar", 0);
AssertCookie (cookies [1], "expires", "World", 635486643190000000);
AssertCookie (cookies [2], "A", "B", 0);
}
[Test]
public void TestInvalidCookie ()
{
var cookies = DoRequest (B);
Assert.AreEqual (3, cookies.Count);
AssertCookie (cookies [0], "A", "B=C");
AssertCookie (cookies [1], "expires", "Sat");
AssertCookie (cookies [2], "Foo", "Bar");
}
[Test]
public void TestLocalCulture ()
{
var old = Thread.CurrentThread.CurrentCulture;
try {
var culture = new CultureInfo ("de-DE");
Thread.CurrentThread.CurrentCulture = culture;
var cookies = DoRequest (C);
Assert.AreEqual (2, cookies.Count);
AssertCookie (cookies [0], "Foo", "Bar");
AssertCookie (cookies [1], "expires", "Montag");
} finally {
Thread.CurrentThread.CurrentCulture = old;
}
}
[Test]
public void TestMultiple ()
{
var cookies = DoRequest (D);
Assert.AreEqual (3, cookies.Count);
AssertCookie (cookies [0], "A", "B");
AssertCookie (cookies [1], "C", "D");
AssertCookie (cookies [2], "G", "H");
}
[Test]
public void TestMultiple2 ()
{
var cookies = DoRequest (E);
Assert.AreEqual (2, cookies.Count);
AssertCookie (cookies [0], "A", string.Empty, 636970206940000000);
AssertCookie (cookies [1], "E", "F");
}
[Test]
public void TestQuotation ()
{
var cookies = DoRequest (F);
Assert.AreEqual (2, cookies.Count);
AssertCookie (cookies [0], "Foo", "\" A, B\"");
AssertCookie (cookies [1], "E", "F");
}
public class Listener : IDisposable
{
Socket socket;
string[] headers;
public Listener (params string[] headers)
{
this.headers = headers;
Start ();
}
void Start ()
{
socket = new Socket (
AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
socket.Bind (new IPEndPoint (IPAddress.Loopback, 0));
socket.Listen (1);
socket.BeginAccept ((result) => {
var accepted = socket.EndAccept (result);
HandleRequest (accepted);
}, null);
}
public void Dispose ()
{
if (socket != null) {
socket.Close ();
socket = null;
}
}
void HandleRequest (Socket accepted)
{
using (var stream = new NetworkStream (accepted)) {
using (var writer = new StreamWriter (stream)) {
writer.WriteLine ("HTTP/1.1 200 OK");
writer.WriteLine ("Content-Type: text/plain");
foreach (var header in headers)
writer.WriteLine (header);
writer.WriteLine ();
writer.WriteLine ("HELLO");
}
}
}
public EndPoint EndPoint {
get { return socket.LocalEndPoint; }
}
public string URI {
get { return string.Format ("http://{0}/", EndPoint); }
}
}
}
}

View File

@@ -0,0 +1,264 @@
//
// CookieTest.cs - NUnit Test Cases for System.Net.Cookie
//
// Authors:
// Lawrence Pit (loz@cable.a2000.nl)
// Martin Willemoes Hansen (mwh@sysrq.dk)
// Daniel Nauck (dna(at)mono-project(dot)de)
//
// (C) 2003 Martin Willemoes Hansen
//
using NUnit.Framework;
using System;
using System.Net;
namespace MonoTests.System.Net
{
[TestFixture]
public class CookieTest
{
[Test]
public void PublicFields ()
{
Cookie c = new Cookie ();
Assert.AreEqual (string.Empty, c.Name, "#A1");
Assert.AreEqual (string.Empty, c.Value, "#A2");
Assert.AreEqual (string.Empty, c.Domain, "#A3");
Assert.AreEqual (string.Empty, c.Port, "#A4");
Assert.AreEqual (string.Empty, c.Comment, "#A5");
Assert.AreEqual (null, c.CommentUri, "#A6");
Assert.IsFalse (c.Discard, "#A7");
Assert.IsFalse (c.Expired, "#A8");
Assert.AreEqual (DateTime.MinValue, c.Expires, "#A9");
#if NET_2_0
Assert.IsFalse (c.HttpOnly, "#A10");
#endif
Assert.AreEqual (string.Empty, c.Path, "#A11");
Assert.IsFalse (c.Secure, "#A12");
Assert.AreEqual (0, c.Version, "#A13");
Assert.AreEqual (string.Empty, c.ToString (), "#A14");
c.Expires = DateTime.Now;
Assert.IsTrue (c.Expired, "#A15");
c.Port = null;
Assert.AreEqual (string.Empty, c.Port, "#A16");
c.Value = null;
Assert.AreEqual (string.Empty, c.Value, "#A17");
}
[Test]
public void Constructors ()
{
Cookie c = new Cookie ("somename", null, null, null);
try
{
c = new Cookie (null, null, null, null);
Assert.Fail ("#1: Name cannot be null");
}
catch (CookieException)
{
}
}
[Test]
public void Name ()
{
Cookie c = new Cookie ("SomeName", "SomeValue");
Assert.AreEqual (c.Name, "SomeName", "#1");
try
{
c.Name = null;
Assert.Fail ("#2a");
}
catch (CookieException)
{
Assert.AreEqual ("SomeName", c.Name, "#2b");
}
try
{
c.Name = "";
Assert.Fail ("#2c");
}
catch (CookieException)
{
Assert.AreEqual ("SomeName", c.Name, "#2d");
}
try
{
c.Name = " ";
Assert.Fail ("#2e");
}
catch (CookieException)
{
// bah! this fails, yet the name is changed..
// inconsistent with previous test
Assert.AreEqual (String.Empty, c.Name, "#2f");
}
try
{
c.Name = "xxx\r\n";
Assert.Fail ("#2g");
}
catch (CookieException)
{
Assert.AreEqual (String.Empty, c.Name, "#2h");
}
try
{
c.Name = "xxx" + (char)0x80;
}
catch (CookieException)
{
Assert.Fail ("#2i");
}
try
{
c.Name = "$omeName";
Assert.Fail ("#3a: Name cannot start with '$' character");
}
catch (CookieException)
{
Assert.AreEqual (String.Empty, c.Name, "#3b");
}
c.Name = "SomeName$";
Assert.AreEqual (c.Name, "SomeName$", "#4");
try
{
c.Name = "Some=Name";
Assert.Fail ("#5a: Name cannot contain '=' character");
}
catch (CookieException)
{
Assert.AreEqual (String.Empty, c.Name, "#5b");
}
c.Name = "domain";
Assert.AreEqual (c.Name, "domain", "#6");
}
[Test]
public void Path ()
{
Cookie c = new Cookie ();
c.Path = "/Whatever";
Assert.AreEqual ("/Whatever", c.Path, "#1");
c.Path = null;
Assert.AreEqual (string.Empty, c.Path, "#2");
c.Path = "ok";
Assert.AreEqual ("ok", c.Path, "#3");
c.Path = string.Empty;
Assert.AreEqual (string.Empty, c.Path, "#4");
}
[Test]
public void Value ()
{
// LAMESPEC: According to .Net specs the Value property should not accept
// the semicolon and comma characters, yet it does
/*
Cookie c = new Cookie("SomeName", "SomeValue");
try {
c.Value = "Some;Value";
Assert.Fail ("#1: semicolon should not be accepted");
} catch (CookieException) {
}
try {
c.Value = "Some,Value";
Assert.Fail ("#2: comma should not be accepted");
} catch (CookieException) {
}
c.Value = "Some\tValue";
Assert.AreEqual (c.Value, "Some\tValue", "#3");
*/
}
[Test]
public void Port ()
{
Cookie c = new Cookie ("SomeName", "SomeValue");
try
{
c.Port = "123";
Assert.Fail ("#1: port must start and end with double quotes");
}
catch (CookieException)
{
}
try
{
Assert.AreEqual (0, c.Version, "#6.1");
c.Port = "\"123\"";
Assert.AreEqual (1, c.Version, "#6.2");
}
catch (CookieException)
{
Assert.Fail ("#2");
}
try
{
c.Port = "\"123;124\"";
Assert.Fail ("#3");
}
catch (CookieException)
{
}
try
{
c.Port = "\"123,123,124\"";
}
catch (CookieException)
{
Assert.Fail ("#4");
}
try
{
c.Port = "\"123,124\"";
}
catch (CookieException)
{
Assert.Fail ("#5");
}
}
[Test]
public void Equals ()
{
Cookie c1 = new Cookie ("NAME", "VALUE", "PATH", "DOMAIN");
Cookie c2 = new Cookie ("name", "value", "path", "domain");
Assert.IsTrue (!c1.Equals (c2), "#1");
c2.Value = "VALUE";
c2.Path = "PATH";
Assert.IsTrue (c1.Equals (c2), "#2");
c2.Version = 1;
Assert.IsTrue (!c1.Equals (c2), "#3");
}
[Test]
public void ToStringTest ()
{
Cookie c1 = new Cookie ("NAME", "VALUE", "/", "example.com");
Assert.AreEqual ("NAME=VALUE", c1.ToString (), "#A1");
Cookie c2 = new Cookie ();
Assert.AreEqual (string.Empty, c2.ToString (), "#A2");
Cookie c3 = new Cookie("NAME", "VALUE");
Assert.AreEqual ("NAME=VALUE", c3.ToString (), "#A3");
Cookie c4 = new Cookie ("NAME", "VALUE", "/", "example.com");
c4.Version = 1;
Assert.AreEqual ("$Version=1; NAME=VALUE; $Path=/; $Domain=example.com", c4.ToString (), "#A4");
Cookie c5 = new Cookie ("NAME", "VALUE", "/", "example.com");
c5.Port = "\"8080\"";
Assert.AreEqual ("$Version=1; NAME=VALUE; $Path=/; $Domain=example.com; $Port=\"8080\"", c5.ToString (), "#A5");
Cookie c6 = new Cookie ("NAME", "VALUE");
c6.Version = 1;
Assert.AreEqual ("$Version=1; NAME=VALUE", c6.ToString (), "#A6");
}
}
}

View File

@@ -0,0 +1,125 @@
//
// CredentialCacheTest.cs - NUnit Test Cases for System.Net.CredentialCache
//
// Author:
// Lawrence Pit (loz@cable.a2000.nl)
//
using NUnit.Framework;
using System;
using System.Net;
using System.Collections;
using System.Security;
using System.Security.Permissions;
namespace MonoTests.System.Net
{
[TestFixture]
public class CredentialCacheTest
{
[Test]
public void All ()
{
CredentialCache c = new CredentialCache ();
NetworkCredential cred1 = new NetworkCredential ("user1", "pwd1");
NetworkCredential cred2 = new NetworkCredential ("user2", "pwd2");
NetworkCredential cred3 = new NetworkCredential ("user3", "pwd3");
NetworkCredential cred4 = new NetworkCredential ("user4", "pwd4");
NetworkCredential cred5 = new NetworkCredential ("user5", "pwd5");
c.Add (new Uri ("http://www.ximian.com"), "Basic", cred1);
c.Add (new Uri ("http://www.ximian.com"), "Kerberos", cred2);
c.Add (new Uri ("http://www.contoso.com/portal/news/index.aspx"), "Basic", cred1);
c.Add (new Uri ("http://www.contoso.com/portal/news/index.aspx?item=1"), "Basic", cred2);
c.Add (new Uri ("http://www.contoso.com/portal/news/index.aspx?item=12"), "Basic", cred3);
c.Add (new Uri ("http://www.contoso.com/portal/"), "Basic", cred4);
c.Add (new Uri ("http://www.contoso.com"), "Basic", cred5);
NetworkCredential result = null;
try {
c.Add (new Uri("http://www.ximian.com"), "Basic", cred1);
Assert.Fail ("#1: should have failed");
} catch (ArgumentException) { }
c.Add (new Uri("http://www.contoso.com/"), "**Unknown**", cred1);
result = c.GetCredential (new Uri("http://www.contoso.com/"), "**Unknown**");
Assert.AreEqual (result, cred1, "#3");
c.Remove (new Uri("http://www.contoso.com/"), "**Unknown**");
result = c.GetCredential (new Uri("http://www.contoso.com/"), "**Unknown**");
Assert.IsTrue (result == null, "#4");
c.Add (new Uri("http://www.contoso.com/"), "**Unknown**", cred1);
result = c.GetCredential (new Uri("http://www.contoso.com"), "**Unknown**");
Assert.AreEqual (result, cred1, "#5");
c.Remove (new Uri("http://www.contoso.com"), "**Unknown**");
result = c.GetCredential (new Uri("http://www.contoso.com"), "**Unknown**");
Assert.IsTrue (result == null, "#6");
c.Add (new Uri("http://www.contoso.com/portal/"), "**Unknown**", cred1);
result = c.GetCredential (new Uri("http://www.contoso.com/portal/foo/bar.html"), "**Unknown**");
Assert.AreEqual (result, cred1, "#7");
c.Remove (new Uri("http://www.contoso.com"), "**Unknown**");
result = c.GetCredential (new Uri("http://www.contoso.com"), "**Unknown**");
Assert.IsTrue (result == null, "#8");
result = c.GetCredential (new Uri("http://www.contoso.com:80/portal/news/index.aspx"), "Basic");
Assert.AreEqual (result, cred3, "#9");
result = c.GetCredential (new Uri("http://www.contoso.com:80/portal/news/index"), "Basic");
Assert.AreEqual (result, cred3, "#10");
result = c.GetCredential (new Uri("http://www.contoso.com:80/portal/news/"), "Basic");
Assert.AreEqual (result, cred3, "#11");
result = c.GetCredential (new Uri("http://www.contoso.com:80/portal/news"), "Basic");
Assert.AreEqual (result, cred4, "#12");
result = c.GetCredential (new Uri("http://www.contoso.com:80/portal/ne"), "Basic");
Assert.AreEqual (result, cred4, "#13");
result = c.GetCredential (new Uri("http://www.contoso.com:80/portal/"), "Basic");
Assert.AreEqual (result, cred4, "#14");
result = c.GetCredential (new Uri("http://www.contoso.com:80/portal"), "Basic");
Assert.AreEqual (result, cred5, "#15");
result = c.GetCredential (new Uri("http://www.contoso.com:80/"), "Basic");
Assert.AreEqual (result, cred5, "#16");
result = c.GetCredential (new Uri("http://www.contoso.com"), "Basic");
Assert.AreEqual (result, cred5, "#17");
/*
IEnumerator e = c.GetEnumerator ();
while (e.MoveNext ()) {
Console.WriteLine (e.Current.GetType () + " : " + e.Current.ToString ());
}
*/
#if NET_2_0
result = c.GetCredential ("www.ximian.com", 80, "Basic");
Assert.IsTrue (result == null, "#18");
c.Add ("www.ximian.com", 80, "Basic", cred1);
try {
c.Add ("www.ximian.com", 80, "Basic", cred1);
Assert.Fail ("#19: should have failed");
} catch (ArgumentException) { }
result = c.GetCredential ("www.ximian.com", 80, "Basic");
Assert.AreEqual (result, cred1, "#20");
c.Remove (new Uri("http://www.contoso.com"), "Basic");
c.Add ("www.contoso.com", 80, "Basic", cred5);
result = c.GetCredential (new Uri("http://www.contoso.com"), "Basic");
Assert.IsTrue (result == null, "#21");
#endif
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,113 @@
//
// DnsPermissionAttributeTest.cs - NUnit Test Cases for DnsPermissionAttribute
//
// Author:
// Sebastien Pouliot <sebastien@ximian.com>
//
// Copyright (C) 2004 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 NUnit.Framework;
using System;
using System.Net;
using System.Security;
using System.Security.Permissions;
namespace MonoTests.System.Net {
[TestFixture]
public class DnsPermissionAttributeTest {
[Test]
public void Default ()
{
DnsPermissionAttribute a = new DnsPermissionAttribute (SecurityAction.Assert);
Assert.AreEqual (a.ToString (), a.TypeId.ToString (), "TypeId");
Assert.IsFalse (a.Unrestricted, "Unrestricted");
DnsPermission perm = (DnsPermission)a.CreatePermission ();
Assert.IsFalse (a.Unrestricted, "Unrestricted");
}
[Test]
public void Action ()
{
DnsPermissionAttribute a = new DnsPermissionAttribute (SecurityAction.Assert);
Assert.AreEqual (SecurityAction.Assert, a.Action, "Action=Assert");
a.Action = SecurityAction.Demand;
Assert.AreEqual (SecurityAction.Demand, a.Action, "Action=Demand");
a.Action = SecurityAction.Deny;
Assert.AreEqual (SecurityAction.Deny, a.Action, "Action=Deny");
a.Action = SecurityAction.InheritanceDemand;
Assert.AreEqual (SecurityAction.InheritanceDemand, a.Action, "Action=InheritanceDemand");
a.Action = SecurityAction.LinkDemand;
Assert.AreEqual (SecurityAction.LinkDemand, a.Action, "Action=LinkDemand");
a.Action = SecurityAction.PermitOnly;
Assert.AreEqual (SecurityAction.PermitOnly, a.Action, "Action=PermitOnly");
a.Action = SecurityAction.RequestMinimum;
Assert.AreEqual (SecurityAction.RequestMinimum, a.Action, "Action=RequestMinimum");
a.Action = SecurityAction.RequestOptional;
Assert.AreEqual (SecurityAction.RequestOptional, a.Action, "Action=RequestOptional");
a.Action = SecurityAction.RequestRefuse;
Assert.AreEqual (SecurityAction.RequestRefuse, a.Action, "Action=RequestRefuse");
}
[Test]
public void Action_Invalid ()
{
DnsPermissionAttribute a = new DnsPermissionAttribute ((SecurityAction)Int32.MinValue);
// no validation in attribute
}
[Test]
public void Unrestricted ()
{
DnsPermissionAttribute a = new DnsPermissionAttribute (SecurityAction.Assert);
a.Unrestricted = true;
DnsPermission dp = (DnsPermission) a.CreatePermission ();
Assert.IsTrue (dp.IsUnrestricted (), "IsUnrestricted");
a.Unrestricted = false;
dp = (DnsPermission)a.CreatePermission ();
Assert.IsFalse (dp.IsUnrestricted (), "!IsUnrestricted");
}
[Test]
public void Attributes ()
{
Type t = typeof (DnsPermissionAttribute);
Assert.IsTrue (t.IsSerializable, "IsSerializable");
object [] attrs = t.GetCustomAttributes (typeof (AttributeUsageAttribute), false);
Assert.AreEqual (1, attrs.Length, "AttributeUsage");
AttributeUsageAttribute aua = (AttributeUsageAttribute)attrs [0];
Assert.IsTrue (aua.AllowMultiple, "AllowMultiple");
Assert.IsFalse (aua.Inherited, "Inherited");
AttributeTargets at = (AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method);
Assert.AreEqual (at, aua.ValidOn, "ValidOn");
}
}
}
#endif

View File

@@ -0,0 +1,251 @@
//
// DnsPermissionTest.cs - NUnit Test Cases for DnsPermission
//
// Author:
// Sebastien Pouliot <sebastien@ximian.com>
//
// Copyright (C) 2004 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 NUnit.Framework;
using System;
using System.Net;
using System.Security;
using System.Security.Permissions;
namespace MonoTests.System.Net {
[TestFixture]
public class DnsPermissionTest {
[Test]
public void PermissionState_None ()
{
PermissionState ps = PermissionState.None;
DnsPermission dp = new DnsPermission (ps);
Assert.IsFalse (dp.IsUnrestricted (), "IsUnrestricted");
SecurityElement se = dp.ToXml ();
// only class and version are present
Assert.AreEqual (2, se.Attributes.Count, "Xml-Attributes#");
Assert.IsNull (se.Children, "Xml-Children");
DnsPermission copy = (DnsPermission)dp.Copy ();
Assert.IsFalse (Object.ReferenceEquals (dp, copy), "ReferenceEquals");
Assert.AreEqual (dp.IsUnrestricted (), copy.IsUnrestricted (), "IsUnrestricted ()");
}
[Test]
public void PermissionState_Unrestricted ()
{
PermissionState ps = PermissionState.Unrestricted;
DnsPermission dp = new DnsPermission (ps);
Assert.IsTrue (dp.IsUnrestricted (), "IsUnrestricted");
SecurityElement se = dp.ToXml ();
Assert.AreEqual ("true", se.Attribute ("Unrestricted"), "Xml-Unrestricted");
Assert.AreEqual (3, se.Attributes.Count, "Xml-Attributes#");
Assert.IsNull (se.Children, "Xml-Children");
DnsPermission copy = (DnsPermission)dp.Copy ();
Assert.IsFalse (Object.ReferenceEquals (dp, copy), "ReferenceEquals");
Assert.AreEqual (dp.IsUnrestricted (), copy.IsUnrestricted (), "IsUnrestricted ()");
}
[Test]
public void PermissionState_Bad ()
{
PermissionState ps = (PermissionState)Int32.MinValue;
DnsPermission dp = new DnsPermission (ps);
// no ArgumentException here
Assert.IsFalse (dp.IsUnrestricted ());
}
[Test]
public void Intersect ()
{
DnsPermission dpn = new DnsPermission (PermissionState.None);
Assert.IsNull (dpn.Intersect (null), "None N null");
Assert.IsNull (dpn.Intersect (dpn), "None N None");
DnsPermission dpu = new DnsPermission (PermissionState.Unrestricted);
Assert.IsNull (dpu.Intersect (null), "Unrestricted N null");
DnsPermission result = (DnsPermission) dpu.Intersect (dpu);
Assert.IsTrue (result.IsUnrestricted (), "Unrestricted N Unrestricted");
Assert.IsNull (dpn.Intersect (dpu), "None N Unrestricted");
Assert.IsNull (dpu.Intersect (dpn), "Unrestricted N None");
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void Intersect_BadPermission ()
{
DnsPermission dp = new DnsPermission (PermissionState.None);
dp.Intersect (new SecurityPermission (PermissionState.Unrestricted));
}
[Test]
public void IsSubset ()
{
DnsPermission dpn = new DnsPermission (PermissionState.None);
DnsPermission dpu = new DnsPermission (PermissionState.Unrestricted);
Assert.IsTrue (dpn.IsSubsetOf (null), "None IsSubsetOf null");
Assert.IsFalse (dpu.IsSubsetOf (null), "Unrestricted IsSubsetOf null");
Assert.IsTrue (dpn.IsSubsetOf (dpn), "None IsSubsetOf None");
Assert.IsTrue (dpu.IsSubsetOf (dpu), "Unrestricted IsSubsetOf Unrestricted");
Assert.IsTrue (dpn.IsSubsetOf (dpu), "None IsSubsetOf Unrestricted");
Assert.IsFalse (dpu.IsSubsetOf (dpn), "Unrestricted IsSubsetOf None");
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void IsSubset_BadPermission ()
{
DnsPermission dp = new DnsPermission (PermissionState.None);
dp.IsSubsetOf (new SecurityPermission (PermissionState.Unrestricted));
}
[Test]
public void Union ()
{
DnsPermission dpn = new DnsPermission (PermissionState.None);
DnsPermission dpu = new DnsPermission (PermissionState.Unrestricted);
DnsPermission result = (DnsPermission) dpn.Union (null);
Assert.IsFalse (result.IsUnrestricted (), "None U null");
result = (DnsPermission) dpu.Union (null);
Assert.IsTrue (result.IsUnrestricted (), "Unrestricted U null");
result = (DnsPermission) dpn.Union (dpn);
Assert.IsFalse (result.IsUnrestricted (), "None U None");
result = (DnsPermission) dpu.Union (dpu);
Assert.IsTrue (result.IsUnrestricted (), "Unrestricted U Unrestricted");
result = (DnsPermission) dpn.Union (dpu);
Assert.IsTrue (result.IsUnrestricted (), "None U Unrestricted");
result = (DnsPermission) dpu.Union (dpn);
Assert.IsTrue (result.IsUnrestricted (), "Unrestricted U None");
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void Union_BadPermission ()
{
DnsPermission dp = new DnsPermission (PermissionState.None);
dp.Union (new SecurityPermission (PermissionState.Unrestricted));
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void FromXml_Null ()
{
DnsPermission dp = new DnsPermission (PermissionState.None);
dp.FromXml (null);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void FromXml_WrongTag ()
{
DnsPermission dp = new DnsPermission (PermissionState.None);
SecurityElement se = dp.ToXml ();
se.Tag = "IMono";
dp.FromXml (se);
// note: normally IPermission classes (in corlib) DO care about the
// IPermission tag
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void FromXml_WrongTagCase ()
{
DnsPermission dp = new DnsPermission (PermissionState.None);
SecurityElement se = dp.ToXml ();
se.Tag = "IPERMISSION"; // instead of IPermission
dp.FromXml (se);
// note: normally IPermission classes (in corlib) DO care about the
// IPermission tag
}
[Test]
public void FromXml_WrongClass ()
{
DnsPermission dp = new DnsPermission (PermissionState.None);
SecurityElement se = dp.ToXml ();
SecurityElement w = new SecurityElement (se.Tag);
w.AddAttribute ("class", "Wrong" + se.Attribute ("class"));
w.AddAttribute ("version", se.Attribute ("version"));
dp.FromXml (w);
// doesn't care of the class name at that stage
// anyway the class has already be created so...
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void FromXml_NoClass ()
{
DnsPermission dp = new DnsPermission (PermissionState.None);
SecurityElement se = dp.ToXml ();
SecurityElement w = new SecurityElement (se.Tag);
w.AddAttribute ("version", se.Attribute ("version"));
dp.FromXml (w);
// note: normally IPermission classes (in corlib) DO NOT care about
// attribute "class" name presence in the XML
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void FromXml_WrongVersion ()
{
DnsPermission dp = new DnsPermission (PermissionState.None);
SecurityElement se = dp.ToXml ();
se.Attributes.Remove ("version");
se.Attributes.Add ("version", "2");
dp.FromXml (se);
}
[Test]
public void FromXml_NoVersion ()
{
DnsPermission dp = new DnsPermission (PermissionState.None);
SecurityElement se = dp.ToXml ();
SecurityElement w = new SecurityElement (se.Tag);
w.AddAttribute ("class", se.Attribute ("class"));
dp.FromXml (w);
}
}
}
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,67 @@
//
// EndPointTest.cs - Unit tests for System.Net.EndPoint
//
// 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.
//
using NUnit.Framework;
using System;
using System.Net;
namespace MonoTests.System.Net {
[TestFixture]
public class EndPointTest {
class ConcreteEndPoint : EndPoint {
}
[Test]
[ExpectedException (typeof (NotImplementedException))]
public void AddressFamily ()
{
ConcreteEndPoint ep = new ConcreteEndPoint ();
Assert.IsNotNull (ep.AddressFamily);
}
[Test]
[ExpectedException (typeof (NotImplementedException))]
public void Create ()
{
ConcreteEndPoint ep = new ConcreteEndPoint ();
Assert.IsNotNull (ep.Create (null));
}
[Test]
[ExpectedException (typeof (NotImplementedException))]
public void Serialize ()
{
ConcreteEndPoint ep = new ConcreteEndPoint ();
Assert.IsNotNull (ep.Serialize ());
}
}
}

View File

@@ -0,0 +1,125 @@
//
// FileWebRequestCas.cs - CAS unit tests for System.Net.WebRequest class
//
// Author:
// Sebastien Pouliot <sebastien@ximian.com>
//
// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
//
using NUnit.Framework;
using System;
using System.IO;
using System.Net;
using System.Security;
using System.Security.Permissions;
using System.Threading;
namespace MonoCasTests.System.Net {
[TestFixture]
[Category ("CAS")]
public class FileWebRequestCas {
private const int timeout = 30000;
static ManualResetEvent reset;
private string message;
private string uri;
private string file;
[TestFixtureSetUp]
public void FixtureSetUp ()
{
reset = new ManualResetEvent (false);
}
[TestFixtureTearDown]
public void FixtureTearDown ()
{
reset.Close ();
}
[SetUp]
public void SetUp ()
{
if (!SecurityManager.SecurityEnabled)
Assert.Ignore ("SecurityManager.SecurityEnabled is OFF");
// unique uri for each test
file = Path.GetTempFileName ();
// to please both Windows and Unix file systems
uri = ((file [0] == '/') ? "file://" : "file:///") + file.Replace ('\\', '/');
}
// async tests (for stack propagation)
private void GetRequestStreamCallback (IAsyncResult ar)
{
FileWebRequest fwr = (FileWebRequest)ar.AsyncState;
fwr.EndGetRequestStream (ar);
try {
// can we do something bad here ?
Assert.IsNotNull (Environment.GetEnvironmentVariable ("USERNAME"));
message = "Expected a SecurityException";
}
catch (SecurityException) {
message = null;
reset.Set ();
}
catch (Exception e) {
message = e.ToString ();
}
}
[Test]
[EnvironmentPermission (SecurityAction.Deny, Read = "USERNAME")]
public void AsyncGetRequestStream ()
{
if (File.Exists (file))
File.Delete (file);
FileWebRequest w = (FileWebRequest)WebRequest.Create (uri);
w.Method = "PUT";
message = "AsyncGetRequestStream";
reset.Reset ();
IAsyncResult r = w.BeginGetRequestStream (new AsyncCallback (GetRequestStreamCallback), w);
Assert.IsNotNull (r, "IAsyncResult");
if (!reset.WaitOne (timeout, true))
Assert.Ignore ("Timeout");
Assert.IsNull (message, message);
}
private void GetResponseCallback (IAsyncResult ar)
{
FileWebRequest fwr = (FileWebRequest)ar.AsyncState;
fwr.EndGetResponse (ar);
try {
// can we do something bad here ?
Assert.IsNotNull (Environment.GetEnvironmentVariable ("USERNAME"));
message = "Expected a SecurityException";
}
catch (SecurityException) {
message = null;
reset.Set ();
}
catch (Exception e) {
message = e.ToString ();
}
}
[Test]
[EnvironmentPermission (SecurityAction.Deny, Read = "USERNAME")]
public void AsyncGetResponse ()
{
FileWebRequest w = (FileWebRequest)WebRequest.Create (uri);
message = "AsyncGetResponse";
reset.Reset ();
IAsyncResult r = w.BeginGetResponse (new AsyncCallback (GetResponseCallback), w);
Assert.IsNotNull (r, "IAsyncResult");
if (!reset.WaitOne (timeout, true))
Assert.Ignore ("Timeout");
Assert.IsNull (message, message);
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,255 @@
//
// FileWebResponseTest.cs - NUnit Test Cases for System.Net.FileWebResponse
//
// Authors:
// Gert Driesen (drieseng@users.sourceforge.net)
//
// (C) 2007 Gert Driesen
//
using System;
using System.IO;
using System.Net;
using NUnit.Framework;
#if TARGET_JVM
using System.Globalization;
using System.Reflection;
#endif
namespace MonoTests.System.Net
{
[TestFixture]
public class FileWebResponseTest
{
private string _tempDirectory;
private string _tempFile;
private Uri _tempFileUri;
[SetUp]
public void SetUp ()
{
_tempDirectory = Path.Combine (Path.GetTempPath (), "MonoTests.System.Net.FileWebResponseTest");
_tempFile = Path.Combine (_tempDirectory, "FileWebResponseTest.tmp");
if (!Directory.Exists (_tempDirectory)) {
Directory.CreateDirectory (_tempDirectory);
} else {
// ensure no files are left over from previous runs
string [] files = Directory.GetFiles (_tempDirectory, "*");
foreach (string file in files)
File.Delete (file);
}
_tempFileUri = GetTempFileUri ();
}
[TearDown]
public void TearDown ()
{
if (Directory.Exists (_tempDirectory)) {
string [] files = Directory.GetFiles (_tempDirectory, "*");
foreach (string file in files)
File.Delete (file);
Directory.Delete (_tempDirectory, true);
}
}
[Test]
public void ContentLength ()
{
FileWebRequest req = (FileWebRequest) WebRequest.Create (_tempFileUri);
req.Method = "PUT";
req.ContentLength = 100;
using (Stream s = req.GetRequestStream ()) {
s.WriteByte (72);
s.WriteByte (110);
s.WriteByte (80);
s.Flush ();
}
req = (FileWebRequest) WebRequest.Create (_tempFileUri);
using (FileWebResponse resp = (FileWebResponse) req.GetResponse ()) {
Assert.AreEqual (3, resp.ContentLength, "#1");
Assert.AreEqual (2, resp.Headers.Count, "#2");
Assert.AreEqual ("Content-Length", resp.Headers.Keys [0], "#3");
Assert.AreEqual ("3", resp.Headers.Get (0), "#4");
resp.Headers.Clear ();
Assert.AreEqual (3, resp.ContentLength, "#5");
Assert.AreEqual (0, resp.Headers.Count, "#6");
}
}
[Test]
public void ContentType ()
{
FileWebRequest req = (FileWebRequest) WebRequest.Create (_tempFileUri);
req.Method = "PUT";
req.ContentType = "image/png";
using (Stream s = req.GetRequestStream ()) {
s.WriteByte (72);
s.WriteByte (110);
s.WriteByte (80);
s.Flush ();
}
req = (FileWebRequest) WebRequest.Create (_tempFileUri);
using (FileWebResponse resp = (FileWebResponse) req.GetResponse ()) {
Assert.AreEqual ("application/octet-stream", resp.ContentType, "#1");
Assert.AreEqual (2, resp.Headers.Count, "#2");
Assert.AreEqual ("Content-Type", resp.Headers.Keys [1], "#3");
Assert.AreEqual ("application/octet-stream", resp.Headers.Get (1), "#4");
resp.Headers.Clear ();
Assert.AreEqual ("application/octet-stream", resp.ContentType, "#5");
Assert.AreEqual (0, resp.Headers.Count, "#6");
}
}
[Test]
public void GetResponseStream ()
{
FileWebRequest req = (FileWebRequest) WebRequest.Create (_tempFileUri);
req.Method = "PUT";
req.ContentType = "image/png";
using (Stream s = req.GetRequestStream ()) {
s.WriteByte (72);
s.WriteByte (110);
s.WriteByte (80);
s.Flush ();
}
req = (FileWebRequest) WebRequest.Create (_tempFileUri);
FileWebResponse respA = null;
FileWebResponse respB = null;
FileStream fsA = null;
FileStream fsB = null;
try {
respA = (FileWebResponse) req.GetResponse ();
fsA = respA.GetResponseStream () as FileStream;
Assert.IsNotNull (fsA, "#A1");
Assert.IsTrue (fsA.CanRead, "#A2");
Assert.IsTrue (fsA.CanSeek, "#A3");
#if NET_2_0
Assert.IsFalse (fsA.CanTimeout, "#A4");
#endif
Assert.IsFalse (fsA.CanWrite, "#A5");
Assert.AreEqual (3, fsA.Length, "#A6");
Assert.AreEqual (0, fsA.Position, "#A7");
#if NET_2_0
try {
int i = fsA.ReadTimeout;
Assert.Fail ("#A8:" + i);
} catch (InvalidOperationException) {
}
try {
int i = fsA.WriteTimeout;
Assert.Fail ("#A9:" + i);
} catch (InvalidOperationException) {
}
#endif
respB = (FileWebResponse) req.GetResponse ();
fsB = respB.GetResponseStream () as FileStream;
Assert.IsNotNull (fsB, "#B1");
Assert.IsTrue (fsB.CanRead, "#B2");
Assert.IsTrue (fsB.CanSeek, "#B3");
#if NET_2_0
Assert.IsFalse (fsB.CanTimeout, "#B4");
#endif
Assert.IsFalse (fsB.CanWrite, "#B5");
Assert.AreEqual (3, fsB.Length, "#B6");
Assert.AreEqual (0, fsB.Position, "#B7");
#if NET_2_0
try {
int i = fsB.ReadTimeout;
Assert.Fail ("#B8:" + i);
} catch (InvalidOperationException) {
}
try {
int i = fsB.WriteTimeout;
Assert.Fail ("#B9:" + i);
} catch (InvalidOperationException) {
}
#endif
} finally {
if (respA != null)
respA.Close ();
if (respB != null)
respB.Close ();
}
}
[Test]
public void Headers ()
{
FileWebRequest req = (FileWebRequest) WebRequest.Create (_tempFileUri);
req.Method = "PUT";
req.Headers.Add ("Disposition", "attach");
using (Stream s = req.GetRequestStream ()) {
s.WriteByte (72);
s.WriteByte (110);
s.WriteByte (80);
s.Flush ();
}
req = (FileWebRequest) WebRequest.Create (_tempFileUri);
using (FileWebResponse resp = (FileWebResponse) req.GetResponse ()) {
Assert.AreEqual (2, resp.Headers.Count, "#1");
Assert.AreEqual ("Content-Length", resp.Headers.Keys [0], "#2");
Assert.AreEqual ("Content-Type", resp.Headers.Keys [1], "#3");
}
}
[Test]
public void ResponseUri ()
{
FileWebRequest req = (FileWebRequest) WebRequest.Create (_tempFileUri);
req.Method = "PUT";
req.ContentType = "image/png";
using (Stream s = req.GetRequestStream ()) {
s.WriteByte (72);
s.WriteByte (110);
s.WriteByte (80);
s.Flush ();
}
req = (FileWebRequest) WebRequest.Create (_tempFileUri);
using (FileWebResponse resp = (FileWebResponse) req.GetResponse ()) {
Assert.AreEqual (_tempFileUri, resp.ResponseUri);
}
}
private Uri GetTempFileUri ()
{
string tempFile = _tempFile;
if (RunningOnUnix) {
// remove leading slash for absolute paths
tempFile = tempFile.TrimStart ('/');
} else {
tempFile = tempFile.Replace ('\\', '/');
}
return new Uri ("file:///" + tempFile);
}
#if TARGET_JVM
private bool RunningOnUnix {
get {
Type t = Type.GetType("java.lang.System");
MethodInfo mi = t.GetMethod("getProperty", new Type[] { typeof(string) });
string osName = (string) mi.Invoke(null, new object[] { "os.name" });
if(osName == null) {
return false;
}
return !osName.StartsWith("win", true, CultureInfo.InvariantCulture);
}
}
#else
private bool RunningOnUnix {
get {
// check for Unix platforms - see FAQ for more details
// http://www.mono-project.com/FAQ:_Technical#How_to_detect_the_execution_platform_.3F
int platform = (int) Environment.OSVersion.Platform;
return ((platform == 4) || (platform == 128));
}
}
#endif
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,79 @@
//
// HttpListenerBasicIdentityTest.cs
// - Unit tests for System.Net.HttpListeneBasicIdentity
//
// Author:
// Gonzalo Paniagua Javier (gonzalo@novell.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.Net;
using NUnit.Framework;
namespace MonoTests.System.Net {
[TestFixture]
#if TARGET_JVM
[Ignore ("The class HttpListenerBasicIdentity - is not supported")]
#endif
public class HttpListenerBasicIdentityTest {
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void Basic1 ()
{
HttpListenerBasicIdentity bi = new HttpListenerBasicIdentity (null, null);
}
[Test]
public void Basic2 ()
{
HttpListenerBasicIdentity bi = new HttpListenerBasicIdentity ("", null);
Assert.AreEqual ("Basic", bi.AuthenticationType, "#01");
Assert.AreEqual ("", bi.Name, "#02");
Assert.IsFalse (bi.IsAuthenticated, "#03");
Assert.IsNull (bi.Password, "#04");
}
[Test]
public void Basic3 ()
{
HttpListenerBasicIdentity bi = new HttpListenerBasicIdentity ("hey", null);
Assert.AreEqual ("Basic", bi.AuthenticationType, "#01");
Assert.AreEqual ("hey", bi.Name, "#02");
Assert.IsTrue (bi.IsAuthenticated, "#03");
Assert.IsNull (bi.Password, "#04");
}
[Test]
public void Basic4 ()
{
HttpListenerBasicIdentity bi = new HttpListenerBasicIdentity ("hey", "pass");
Assert.AreEqual ("Basic", bi.AuthenticationType, "#01");
Assert.AreEqual ("hey", bi.Name, "#02");
Assert.IsTrue (bi.IsAuthenticated, "#03");
Assert.AreEqual ("pass", bi.Password, "#04");
}
}
}
#endif

View File

@@ -0,0 +1,257 @@
//
// HttpListenerPrefixCollectionTest.cs
// - Unit tests for System.Net.HttpListenePrefixCollection
//
// Author:
// Gonzalo Paniagua Javier (gonzalo@novell.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.Net;
using NUnit.Framework;
using HLPC=System.Net.HttpListenerPrefixCollection;
namespace MonoTests.System.Net {
[TestFixture]
#if TARGET_JVM
[Ignore ("The class System.Net.HttpListenerPrefixCollection - is not supported")]
#endif
public class HttpListenerPrefixCollectionTest {
#if !TARGET_JVM
// NL -> Not listening -> tests when listener.IsListening == false
[Test]
public void NL_DefaultProperties ()
{
HttpListener listener = new HttpListener ();
HLPC coll = listener.Prefixes;
Assert.AreEqual (0, coll.Count, "Count");
Assert.IsFalse (coll.IsReadOnly, "IsReadOnly");
Assert.IsFalse (coll.IsSynchronized, "IsSynchronized");
}
[Test]
public void DefaultProperties ()
{
HttpListener listener = new HttpListener ();
HLPC coll = listener.Prefixes;
coll.Add ("http://127.0.0.1:8181/");
Assert.AreEqual (1, coll.Count, "Count");
Assert.IsFalse (coll.IsReadOnly, "IsReadOnly");
Assert.IsFalse (coll.IsSynchronized, "IsSynchronized");
}
[Test]
public void AddOne ()
{
HttpListener listener = new HttpListener ();
HLPC coll = listener.Prefixes;
listener.Start ();
coll.Add ("http://127.0.0.1:8181/");
Assert.AreEqual (1, coll.Count, "Count");
Assert.IsFalse (coll.IsReadOnly, "IsReadOnly");
Assert.IsFalse (coll.IsSynchronized, "IsSynchronized");
listener.Stop ();
}
[Test]
public void Duplicate ()
{
HttpListener listener = new HttpListener ();
HLPC coll = listener.Prefixes;
coll.Add ("http://127.0.0.1:8181/");
coll.Add ("http://127.0.0.1:8181/");
listener.Start ();
Assert.AreEqual (1, coll.Count, "Count");
Assert.IsFalse (coll.IsReadOnly, "IsReadOnly");
Assert.IsFalse (coll.IsSynchronized, "IsSynchronized");
listener.Stop ();
}
[Test]
public void EndsWithSlash ()
{
HttpListener listener = new HttpListener ();
listener.Prefixes.Add ("http://127.0.0.1:7777/");
}
[Test]
public void DifferentPath ()
{
HttpListener listener = new HttpListener ();
listener.Prefixes.Add ("http://127.0.0.1:7777/");
listener.Prefixes.Add ("http://127.0.0.1:7777/hola/");
Assert.AreEqual (2, listener.Prefixes.Count, "#01");
}
[Test]
public void NL_Clear ()
{
HttpListener listener = new HttpListener ();
HLPC coll = listener.Prefixes;
coll.Clear ();
}
[Test]
public void NL_Remove ()
{
HttpListener listener = new HttpListener ();
HLPC coll = listener.Prefixes;
Assert.IsFalse (coll.Remove ("http://127.0.0.1:8181/"));
}
[Test]
public void NL_RemoveBadUri ()
{
HttpListener listener = new HttpListener ();
HLPC coll = listener.Prefixes;
Assert.IsFalse (coll.Remove ("httpblah://127.0.0.1:8181/"));
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void NL_AddBadUri ()
{
HttpListener listener = new HttpListener ();
HLPC coll = listener.Prefixes;
coll.Add ("httpblah://127.0.0.1:8181/");
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void NoHostInUrl ()
{
HttpListener listener = new HttpListener ();
listener.Prefixes.Add ("http://:7777/hola/");
}
[Test]
public void MultipleSlashes ()
{
// this one throws on Start(), not when adding it.
// See same test name in HttpListenerTest.
HttpListener listener = new HttpListener ();
HLPC coll = listener.Prefixes;
coll.Add ("http://localhost:7777/hola////");
string [] strs = new string [1];
coll.CopyTo (strs, 0);
Assert.AreEqual ("http://localhost:7777/hola////", strs [0]);
}
[Test]
public void PercentSign ()
{
HttpListener listener = new HttpListener ();
HLPC coll = listener.Prefixes;
// this one throws on Start(), not when adding it.
// See same test name in HttpListenerTest.
coll.Add ("http://localhost:7777/hola%3E/");
string [] strs = new string [1];
coll.CopyTo (strs, 0);
Assert.AreEqual ("http://localhost:7777/hola%3E/", strs [0]);
}
[Test]
public void Disposed1 ()
{
HttpListener listener = new HttpListener ();
HLPC coll = listener.Prefixes;
listener.Close ();
Assert.AreEqual (0, coll.Count, "Count");
Assert.IsFalse (coll.IsReadOnly, "IsReadOnly");
Assert.IsFalse (coll.IsSynchronized, "IsSynchronized");
}
[Test]
[ExpectedException (typeof (ObjectDisposedException))]
public void Disposed2 ()
{
HttpListener listener = new HttpListener ();
HLPC coll = listener.Prefixes;
listener.Close ();
coll.Add ("http://localhost:7777/hola/");
}
[Test]
[ExpectedException (typeof (ObjectDisposedException))]
public void Disposed3 ()
{
HttpListener listener = new HttpListener ();
HLPC coll = listener.Prefixes;
listener.Close ();
coll.Clear ();
}
[Test]
[ExpectedException (typeof (ObjectDisposedException))]
public void Disposed4 ()
{
HttpListener listener = new HttpListener ();
HLPC coll = listener.Prefixes;
listener.Close ();
coll.Remove ("http://localhost:7777/hola/");
}
[Test]
[ExpectedException (typeof (ObjectDisposedException))]
public void Disposed5 ()
{
HttpListener listener = new HttpListener ();
HLPC coll = listener.Prefixes;
listener.Close ();
string [] strs = new string [0];
coll.CopyTo (strs, 0);
}
[Test]
public void Disposed6 ()
{
HttpListener listener = new HttpListener ();
HLPC coll = listener.Prefixes;
listener.Close ();
string a = null;
foreach (string s in coll) {
a = s; // just to make the compiler happy
}
Assert.IsNull (a);
}
[Test]
public void Disposed7 ()
{
HttpListener listener = new HttpListener ();
HLPC coll = listener.Prefixes;
coll.Add ("http://127.0.0.1/");
listener.Close ();
int items = 0;
foreach (string s in coll) {
items++;
Assert.AreEqual (s, "http://127.0.0.1/");
}
Assert.AreEqual (items, 1);
}
#endif
}
}
#endif

View File

@@ -0,0 +1,191 @@
//
// HttpListenerRequestTest.cs - Unit tests for System.Net.HttpListenerRequest
//
// Authors:
// Gert Driesen (drieseng@users.sourceforge.net)
// David Straw
//
// Copyright (C) 2007 Gert Driesen
//
// 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.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using NUnit.Framework;
namespace MonoTests.System.Net
{
[TestFixture]
#if TARGET_JVM
[Ignore ("The class HttpListener is not supported")]
#endif
public class HttpListenerRequestTest
{
[Test]
[Category ("NotWorking")] // Bug #5742
public void HasEntityBody ()
{
HttpListenerContext ctx;
HttpListenerRequest request;
NetworkStream ns;
HttpListener listener = HttpListener2Test.CreateAndStartListener (
"http://127.0.0.1:9000/HasEntityBody/");
// POST with non-zero Content-Lenth
ns = HttpListener2Test.CreateNS (9000);
HttpListener2Test.Send (ns, "POST /HasEntityBody/ HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Length: 3\r\n\r\n123");
ctx = listener.GetContext ();
request = ctx.Request;
Assert.IsTrue (request.HasEntityBody, "#A");
HttpListener2Test.Send (ctx.Response.OutputStream, "%%%OK%%%");
// POST with zero Content-Lenth
ns = HttpListener2Test.CreateNS (9000);
HttpListener2Test.Send (ns, "POST /HasEntityBody/ HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Length: 0\r\n\r\n123");
ctx = listener.GetContext ();
request = ctx.Request;
Assert.IsFalse (request.HasEntityBody, "#B");
HttpListener2Test.Send (ctx.Response.OutputStream, "%%%OK%%%");
// POST with chunked encoding
ns = HttpListener2Test.CreateNS (9000);
HttpListener2Test.Send (ns, "POST /HasEntityBody HTTP/1.1\r\nHost: 127.0.0.1\r\nTransfer-Encoding: chunked\r\n\r\n0\r\n");
ctx = listener.GetContext ();
request = ctx.Request;
Assert.IsTrue (request.HasEntityBody, "#C");
HttpListener2Test.Send (ctx.Response.OutputStream, "%%%OK%%%");
// GET with no Content-Length
ns = HttpListener2Test.CreateNS (9000);
HttpListener2Test.Send (ns, "GET /HasEntityBody HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n");
ctx = listener.GetContext ();
request = ctx.Request;
Assert.IsFalse (request.HasEntityBody, "#D");
HttpListener2Test.Send (ctx.Response.OutputStream, "%%%OK%%%");
// GET with non-zero Content-Length
ns = HttpListener2Test.CreateNS (9000);
HttpListener2Test.Send (ns, "GET /HasEntityBody HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Length: 3\r\n\r\n");
ctx = listener.GetContext ();
request = ctx.Request;
Assert.IsTrue (request.HasEntityBody, "#E");
HttpListener2Test.Send (ctx.Response.OutputStream, "%%%OK%%%");
// GET with zero Content-Length
ns = HttpListener2Test.CreateNS (9000);
HttpListener2Test.Send (ns, "GET /HasEntityBody HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Length: 0\r\n\r\n");
ctx = listener.GetContext ();
request = ctx.Request;
Assert.IsFalse (request.HasEntityBody, "#F");
HttpListener2Test.Send (ctx.Response.OutputStream, "%%%OK%%%");
// GET with chunked encoding
ns = HttpListener2Test.CreateNS (9000);
HttpListener2Test.Send (ns, "GET /HasEntityBody HTTP/1.1\r\nHost: 127.0.0.1\r\nTransfer-Encoding: chunked\r\n\r\n0\r\n");
ctx = listener.GetContext ();
request = ctx.Request;
Assert.IsTrue (request.HasEntityBody, "#G");
HttpListener2Test.Send (ctx.Response.OutputStream, "%%%OK%%%");
// PUT with non-zero Content-Lenth
ns = HttpListener2Test.CreateNS (9000);
HttpListener2Test.Send (ns, "PUT /HasEntityBody/ HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Length: 3\r\n\r\n123");
ctx = listener.GetContext ();
request = ctx.Request;
Assert.IsTrue (request.HasEntityBody, "#H");
// PUT with zero Content-Lenth
ns = HttpListener2Test.CreateNS (9000);
HttpListener2Test.Send (ns, "PUT /HasEntityBody/ HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Length: 0\r\n\r\n123");
ctx = listener.GetContext ();
request = ctx.Request;
Assert.IsFalse (request.HasEntityBody, "#I");
// INVALID with non-zero Content-Lenth
ns = HttpListener2Test.CreateNS (9000);
HttpListener2Test.Send (ns, "INVALID /HasEntityBody/ HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Length: 3\r\n\r\n123");
ctx = listener.GetContext ();
request = ctx.Request;
Assert.IsTrue (request.HasEntityBody, "#J");
// INVALID with zero Content-Lenth
ns = HttpListener2Test.CreateNS (9000);
HttpListener2Test.Send (ns, "INVALID /HasEntityBody/ HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Length: 0\r\n\r\n123");
ctx = listener.GetContext ();
request = ctx.Request;
Assert.IsFalse (request.HasEntityBody, "#K");
// INVALID with chunked encoding
ns = HttpListener2Test.CreateNS (9000);
HttpListener2Test.Send (ns, "INVALID /HasEntityBody/ HTTP/1.1\r\nHost: 127.0.0.1\r\nTransfer-Encoding: chunked\r\n\r\n0\r\n");
ctx = listener.GetContext ();
request = ctx.Request;
Assert.IsTrue (request.HasEntityBody, "#L");
listener.Close ();
}
[Test]
public void HttpMethod ()
{
HttpListener listener = HttpListener2Test.CreateAndStartListener (
"http://127.0.0.1:9000/HttpMethod/");
NetworkStream ns = HttpListener2Test.CreateNS (9000);
HttpListener2Test.Send (ns, "pOsT /HttpMethod/ HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Length: 3\r\n\r\n123");
HttpListenerContext ctx = listener.GetContext ();
HttpListenerRequest request = ctx.Request;
Assert.AreEqual ("pOsT", request.HttpMethod);
listener.Close ();
}
[Test]
public void HttpBasicAuthScheme ()
{
HttpListener listener = HttpListener2Test.CreateAndStartListener ("http://*:9000/authTest/", AuthenticationSchemes.Basic);
//dummy-wait for context
listener.BeginGetContext (null, listener);
NetworkStream ns = HttpListener2Test.CreateNS (9000);
HttpListener2Test.Send (ns, "GET /authTest/ HTTP/1.0\r\n\r\n");
String response = HttpListener2Test.Receive (ns, 512);
Assert.IsTrue (response.Contains ("WWW-Authenticate: Basic realm"), "#A");
ns.Close ();
listener.Close ();
}
[Test]
public void HttpRequestUriIsNotDecoded ()
{
HttpListener listener = HttpListener2Test.CreateAndStartListener (
"http://127.0.0.1:9000/RequestUriDecodeTest/");
NetworkStream ns = HttpListener2Test.CreateNS (9000);
HttpListener2Test.Send (ns, "GET /RequestUriDecodeTest/?a=b&c=d%26e HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n");
HttpListenerContext ctx = listener.GetContext ();
HttpListenerRequest request = ctx.Request;
Assert.AreEqual ("/RequestUriDecodeTest/?a=b&c=d%26e", request.Url.PathAndQuery);
listener.Close ();
}
}
}

View File

@@ -0,0 +1,461 @@
//
// HttpListenerTest.cs
// - Unit tests for System.Net.HttpListener
//
// Author:
// Gonzalo Paniagua Javier (gonzalo@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.Net;
using System.Net.Sockets;
using System.Threading;
using NUnit.Framework;
namespace MonoTests.System.Net {
[TestFixture]
#if TARGET_JVM
[Ignore ("The class HttpListener is not implemented")]
#endif
public class HttpListenerTest {
#if !TARGET_JVM
[Test]
public void DefaultProperties ()
{
HttpListener listener = new HttpListener ();
Assert.AreEqual (AuthenticationSchemes.Anonymous, listener.AuthenticationSchemes, "#01");
Assert.AreEqual (null, listener.AuthenticationSchemeSelectorDelegate, "#02");
Assert.AreEqual (false, listener.IgnoreWriteExceptions, "#03");
Assert.AreEqual (false, listener.IsListening, "#03");
Assert.AreEqual (0, listener.Prefixes.Count, "#04");
Assert.AreEqual (null, listener.Realm, "#05");
Assert.AreEqual (false, listener.UnsafeConnectionNtlmAuthentication, "#06");
}
[Test]
public void Start1 ()
{
HttpListener listener = new HttpListener ();
listener.Start ();
}
[Test]
public void Stop1 ()
{
HttpListener listener = new HttpListener ();
listener.Stop ();
}
[Test]
[ExpectedException (typeof (InvalidOperationException))]
public void GetContext1 ()
{
HttpListener listener = new HttpListener ();
// "Please call Start () before calling this method"
listener.GetContext ();
}
[Test]
[ExpectedException (typeof (InvalidOperationException))]
public void GetContext2 ()
{
HttpListener listener = new HttpListener ();
listener.Start ();
// "Please call AddPrefix () before calling this method"
listener.GetContext ();
}
[Test]
[ExpectedException (typeof (InvalidOperationException))]
public void BeginGetContext1 ()
{
HttpListener listener = new HttpListener ();
// "Please call Start () before calling this method"
listener.BeginGetContext (null, null);
}
[Test]
public void BeginGetContext2 ()
{
HttpListener listener = new HttpListener ();
listener.Start ();
// One would expect this to fail as BeginGetContext1 does not fail and
// calling EndGetContext will wait forever.
// Lame. They should check that we have no prefixes.
IAsyncResult ares = listener.BeginGetContext (null, null);
Assert.IsFalse (ares.IsCompleted);
}
private bool CanOpenPort(int port)
{
try
{
using(Socket socket = new Socket (AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp))
{
socket.Bind (new IPEndPoint (IPAddress.Loopback, port));
socket.Listen(1);
}
}
catch(Exception ex) {
//Can be AccessDeniedException(ports 80/443 need root access) or
//SocketException because other application is listening
return false;
}
return true;
}
[Test]
public void DefaultHttpPort ()
{
if (!CanOpenPort (80))
Assert.Ignore ("Can not open port 80 skipping test.");
using(HttpListener listener = new HttpListener ())
{
listener.Prefixes.Add ("http://127.0.0.1/");
listener.Start ();
Assert.IsFalse (CanOpenPort (80), "HttpListener is not listening on port 80.");
}
}
[Test]
public void DefaultHttpsPort ()
{
if (!CanOpenPort (443))
Assert.Ignore ("Can not open port 443 skipping test.");
using(HttpListener listener = new HttpListener ())
{
listener.Prefixes.Add ("https://127.0.0.1/");
listener.Start ();
Assert.IsFalse (CanOpenPort (443), "HttpListener is not listening on port 443.");
}
}
[Test]
public void TwoListeners_SameAddress ()
{
HttpListener listener1 = new HttpListener ();
listener1.Prefixes.Add ("http://127.0.0.1:7777/");
HttpListener listener2 = new HttpListener ();
listener2.Prefixes.Add ("http://127.0.0.1:7777/hola/");
listener1.Start ();
listener2.Start ();
}
[Test]
[ExpectedException (typeof (HttpListenerException))]
public void TwoListeners_SameURL ()
{
HttpListener listener1 = new HttpListener ();
listener1.Prefixes.Add ("http://127.0.0.1:7777/hola/");
HttpListener listener2 = new HttpListener ();
listener2.Prefixes.Add ("http://127.0.0.1:7777/hola/");
listener1.Start ();
listener2.Start ();
}
[Test]
[ExpectedException (typeof (HttpListenerException))]
public void MultipleSlashes ()
{
HttpListener listener = new HttpListener ();
listener.Prefixes.Add ("http://localhost:7777/hola////");
// this one throws on Start(), not when adding it.
listener.Start ();
}
[Test]
[ExpectedException (typeof (HttpListenerException))]
public void PercentSign ()
{
HttpListener listener = new HttpListener ();
listener.Prefixes.Add ("http://localhost:7777/hola%3E/");
// this one throws on Start(), not when adding it.
listener.Start ();
}
[Test]
public void CloseBeforeStart ()
{
HttpListener listener = new HttpListener ();
listener.Close ();
}
[Test]
public void CloseTwice ()
{
HttpListener listener = new HttpListener ();
listener.Prefixes.Add ("http://localhost:7777/hola/");
listener.Start ();
listener.Close ();
listener.Close ();
}
[Test]
public void StartStopStart ()
{
HttpListener listener = new HttpListener ();
listener.Prefixes.Add ("http://localhost:7777/hola/");
listener.Start ();
listener.Stop ();
listener.Start ();
listener.Close ();
}
[Test]
public void StartStopDispose ()
{
using (HttpListener listener = new HttpListener ()){
listener.Prefixes.Add ("http://localhost:7777/hola/");
listener.Start ();
listener.Stop ();
}
}
[Test]
public void AbortBeforeStart ()
{
HttpListener listener = new HttpListener ();
listener.Abort ();
}
[Test]
public void AbortTwice ()
{
HttpListener listener = new HttpListener ();
listener.Prefixes.Add ("http://localhost:7777/hola/");
listener.Start ();
listener.Abort ();
listener.Abort ();
}
[Test]
public void PropertiesWhenClosed1 ()
{
HttpListener listener = new HttpListener ();
listener.Close ();
Assert.AreEqual (AuthenticationSchemes.Anonymous, listener.AuthenticationSchemes, "#01");
Assert.AreEqual (null, listener.AuthenticationSchemeSelectorDelegate, "#02");
Assert.AreEqual (false, listener.IgnoreWriteExceptions, "#03");
Assert.AreEqual (false, listener.IsListening, "#03");
Assert.AreEqual (null, listener.Realm, "#05");
Assert.AreEqual (false, listener.UnsafeConnectionNtlmAuthentication, "#06");
}
[Test]
[ExpectedException (typeof (ObjectDisposedException))]
public void PropertiesWhenClosed2 ()
{
HttpListener listener = new HttpListener ();
listener.Close ();
HttpListenerPrefixCollection p = listener.Prefixes;
}
[Test]
[ExpectedException (typeof (ObjectDisposedException))]
public void PropertiesWhenClosedSet1 ()
{
HttpListener listener = new HttpListener ();
listener.Close ();
listener.AuthenticationSchemes = AuthenticationSchemes.None;
}
[Test]
[ExpectedException (typeof (ObjectDisposedException))]
public void PropertiesWhenClosedSet2 ()
{
HttpListener listener = new HttpListener ();
listener.Close ();
listener.AuthenticationSchemeSelectorDelegate = null;
}
[Test]
[ExpectedException (typeof (ObjectDisposedException))]
public void PropertiesWhenClosedSet3 ()
{
HttpListener listener = new HttpListener ();
listener.Close ();
listener.IgnoreWriteExceptions = true;
}
[Test]
[ExpectedException (typeof (ObjectDisposedException))]
public void PropertiesWhenClosedSet4 ()
{
HttpListener listener = new HttpListener ();
listener.Close ();
listener.Realm = "hola";
}
[Test]
[ExpectedException (typeof (ObjectDisposedException))]
public void PropertiesWhenClosedSet5 ()
{
HttpListener listener = new HttpListener ();
listener.Close ();
listener.UnsafeConnectionNtlmAuthentication = true;
}
[Test]
public void PropertiesWhenClosed3 ()
{
HttpListener listener = new HttpListener ();
listener.Close ();
Assert.IsFalse (listener.IsListening);
}
[Test]
public void CloseWhileBegin ()
{
HttpListener listener = new HttpListener ();
listener.Prefixes.Add ("http://127.0.0.1:9001/closewhilebegin/");
listener.Start ();
CallMe cm = new CallMe ();
listener.BeginGetContext (cm.Callback, listener);
listener.Close ();
if (false == cm.Event.WaitOne (3000, false))
Assert.Fail ("This should not time out.");
Assert.IsNotNull (cm.Error);
Assert.AreEqual (typeof (ObjectDisposedException), cm.Error.GetType (), "Exception type");
cm.Dispose ();
}
[Test]
public void AbortWhileBegin ()
{
HttpListener listener = new HttpListener ();
listener.Prefixes.Add ("http://127.0.0.1:9001/abortwhilebegin/");
listener.Start ();
CallMe cm = new CallMe ();
listener.BeginGetContext (cm.Callback, listener);
listener.Abort ();
if (false == cm.Event.WaitOne (3000, false))
Assert.Fail ("This should not time out.");
Assert.IsNotNull (cm.Error);
Assert.AreEqual (typeof (ObjectDisposedException), cm.Error.GetType (), "Exception type");
cm.Dispose ();
}
[Test]
[ExpectedException (typeof (HttpListenerException))]
public void CloseWhileGet ()
{
// "System.Net.HttpListener Exception : The I/O operation has been aborted
// because of either a thread exit or an application request
// at System.Net.HttpListener.GetContext()
// at MonoTests.System.Net.HttpListenerTest.CloseWhileGet()
HttpListener listener = new HttpListener ();
listener.Prefixes.Add ("http://127.0.0.1:9001/closewhileget/");
listener.Start ();
RunMe rm = new RunMe (1000, new ThreadStart (listener.Close), new object [0]);
rm.Start ();
HttpListenerContext ctx = listener.GetContext ();
}
[Test]
[ExpectedException (typeof (HttpListenerException))]
public void AbortWhileGet ()
{
// "System.Net.HttpListener Exception : The I/O operation has been aborted
// because of either a thread exit or an application request
// at System.Net.HttpListener.GetContext()
// at MonoTests.System.Net.HttpListenerTest.CloseWhileGet()
HttpListener listener = new HttpListener ();
listener.Prefixes.Add ("http://127.0.0.1:9001/abortwhileget/");
listener.Start ();
RunMe rm = new RunMe (1000, new ThreadStart (listener.Abort), new object [0]);
rm.Start ();
HttpListenerContext ctx = listener.GetContext ();
}
class RunMe {
Delegate d;
int delay_ms;
object [] args;
public object Result;
public RunMe (int delay_ms, Delegate d, object [] args)
{
this.delay_ms = delay_ms;
this.d = d;
this.args = args;
}
public void Start ()
{
Thread th = new Thread (new ThreadStart (Run));
th.Start ();
}
void Run ()
{
Thread.Sleep (delay_ms);
Result = d.DynamicInvoke (args);
}
}
class CallMe {
public ManualResetEvent Event = new ManualResetEvent (false);
public bool Called;
public HttpListenerContext Context;
public Exception Error;
public void Reset ()
{
Called = false;
Context = null;
Error = null;
Event.Reset ();
}
public void Callback (IAsyncResult ares)
{
Called = true;
if (ares == null) {
Error = new ArgumentNullException ("ares");
return;
}
try {
HttpListener listener = (HttpListener) ares.AsyncState;
Context = listener.EndGetContext (ares);
} catch (Exception e) {
Error = e;
}
Event.Set ();
}
public void Dispose ()
{
Event.Close ();
}
}
#endif
}
}
#endif

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