Removed Spring.Http project (moved to GitHub project spring-net-rest) (SPRNET-1345)

This commit is contained in:
bbaia
2011-02-04 19:10:36 +00:00
parent ab3f4dedea
commit 5532f67a9d
161 changed files with 0 additions and 38784 deletions

View File

@@ -1,25 +0,0 @@
#region License
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyTitle("Spring.Http Tests")]
[assembly: AssemblyDescription("Unit tests for Spring.Http assembly")]

View File

@@ -1,440 +0,0 @@
#if NET_3_5
#region License
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System;
using System.IO;
using System.Net;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Threading;
using NUnit.Framework;
namespace Spring.Http.Client
{
/// <summary>
/// Integration tests for IClientHttpRequestFactory implementations.
/// </summary>
/// <author>Arjen Poutsma</author>
/// <author>Bruno Baia (.NET)</author>
[TestFixture]
public abstract class AbstractClientHttpRequestFactoryIntegrationTests
{
private IClientHttpRequestFactory requestFactory;
private const string BASE_URL = "http://localhost:1337";
private WebServiceHost webServiceHost;
[SetUp]
public void SetUp()
{
requestFactory = this.CreateRequestFactory();
webServiceHost = new WebServiceHost(typeof(TestService), new Uri(BASE_URL));
this.ConfigureWebServiceHost(webServiceHost);
webServiceHost.Open();
}
[TearDown]
public void TearDown()
{
webServiceHost.Close();
}
protected abstract IClientHttpRequestFactory CreateRequestFactory();
protected virtual void ConfigureWebServiceHost(WebServiceHost webServiceHost)
{
}
protected virtual IClientHttpRequest CreateRequest(string path, HttpMethod method)
{
Uri uri = new Uri(BASE_URL + path);
IClientHttpRequest request = requestFactory.CreateRequest(uri, method);
Assert.AreEqual(method, request.Method, "Invalid HTTP method");
Assert.AreEqual(uri, request.Uri, "Invalid HTTP URI");
return request;
}
#region Sync
[Test]
public void Status()
{
IClientHttpRequest request = this.CreateRequest("/status/notfound", HttpMethod.GET);
using (IClientHttpResponse response = request.Execute())
{
Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode, "Invalid status code");
Assert.AreEqual("Status NotFound", response.StatusDescription, "Invalid status description");
}
}
[Test]
public void Echo()
{
IClientHttpRequest request = this.CreateRequest("/echo", HttpMethod.PUT);
request.Headers.ContentType = new MediaType("text", "plain", "utf-8");
String headerName = "MyHeader";
String headerValue1 = "value1";
request.Headers.Add(headerName, headerValue1);
String headerValue2 = "value2";
request.Headers.Add(headerName, headerValue2);
byte[] body = Encoding.UTF8.GetBytes("Hello World");
request.Body = delegate(Stream stream)
{
stream.Write(body, 0, body.Length);
};
using (IClientHttpResponse response = request.Execute())
{
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, "Invalid status code");
Assert.AreEqual("value1,value2", response.Headers[headerName], "Header values not found");
using (BinaryReader reader = new BinaryReader(response.Body))
{
byte[] result = reader.ReadBytes((int)response.Headers.ContentLength);
Assert.AreEqual(body, result, "Invalid body");
}
}
}
[Test]
[ExpectedException(typeof(InvalidOperationException),
ExpectedMessage = "Client HTTP request already executed or is currently executing.")]
public void MultipleExecute()
{
IClientHttpRequest request = this.CreateRequest("/status/ok", HttpMethod.GET);
request.Execute();
request.Execute();
}
[Test]
public void HttpMethods()
{
AssertHttpMethod("get", HttpMethod.GET);
AssertHttpMethod("head", HttpMethod.HEAD);
AssertHttpMethod("post", HttpMethod.POST);
AssertHttpMethod("put", HttpMethod.PUT);
AssertHttpMethod("options", HttpMethod.OPTIONS);
AssertHttpMethod("delete", HttpMethod.DELETE);
}
private void AssertHttpMethod(String path, HttpMethod method)
{
IClientHttpRequest request = this.CreateRequest("/methods/" + path, method);
request.Headers.ContentLength = 0; // TODO : post/put null
using (IClientHttpResponse response = request.Execute())
{
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, "Invalid status code");
Assert.AreEqual(path, response.StatusDescription, "Invalid status description");
}
}
#endregion
#region Async
[Test]
public void StatusAsync()
{
ManualResetEvent manualEvent = new ManualResetEvent(false);
Exception exception = null;
IClientHttpRequest request = this.CreateRequest("/status/notfound", HttpMethod.GET);
request.ExecuteAsync(null, delegate(ExecuteCompletedEventArgs args)
{
try
{
Assert.IsNull(args.Error, "Invalid response");
Assert.IsFalse(args.Cancelled, "Invalid response");
Assert.AreEqual(HttpStatusCode.NotFound, args.Response.StatusCode, "Invalid status code");
Assert.AreEqual("Status NotFound", args.Response.StatusDescription, "Invalid status description");
}
catch(Exception ex)
{
exception = ex;
}
finally
{
manualEvent.Set();
}
});
manualEvent.WaitOne();
if (exception != null)
{
throw exception;
}
}
[Test]
public void EchoAsync()
{
ManualResetEvent manualEvent = new ManualResetEvent(false);
Exception exception = null;
IClientHttpRequest request = this.CreateRequest("/echo", HttpMethod.PUT);
request.Headers.ContentType = new MediaType("text", "plain", "utf-8");
String headerName = "MyHeader";
String headerValue1 = "value1";
request.Headers.Add(headerName, headerValue1);
String headerValue2 = "value2";
request.Headers.Add(headerName, headerValue2);
byte[] body = Encoding.UTF8.GetBytes("Hello World");
request.Body = delegate(Stream stream)
{
stream.Write(body, 0, body.Length);
};
request.ExecuteAsync(null, delegate(ExecuteCompletedEventArgs args)
{
try
{
Assert.IsNull(args.Error, "Invalid response");
Assert.IsFalse(args.Cancelled, "Invalid response");
Assert.AreEqual(HttpStatusCode.OK, args.Response.StatusCode, "Invalid status code");
Assert.AreEqual("value1,value2", args.Response.Headers[headerName], "Header values not found");
using (BinaryReader reader = new BinaryReader(args.Response.Body))
{
byte[] result = reader.ReadBytes((int)args.Response.Headers.ContentLength);
Assert.AreEqual(body, result, "Invalid body");
}
}
catch (Exception ex)
{
exception = ex;
}
finally
{
manualEvent.Set();
}
});
manualEvent.WaitOne();
if (exception != null)
{
throw exception;
}
}
[Test]
[ExpectedException(typeof(InvalidOperationException),
ExpectedMessage = "Client HTTP request already executed or is currently executing.")]
public void MultipleExecuteAsync()
{
IClientHttpRequest request = this.CreateRequest("/status/ok", HttpMethod.GET);
request.ExecuteAsync(null, null);
request.ExecuteAsync(null, null);
}
[Test]
public void HttpMethodsAsync()
{
AssertHttpMethodAsync("get", HttpMethod.GET);
AssertHttpMethodAsync("head", HttpMethod.HEAD);
AssertHttpMethodAsync("post", HttpMethod.POST);
AssertHttpMethodAsync("put", HttpMethod.PUT);
AssertHttpMethodAsync("options", HttpMethod.OPTIONS);
AssertHttpMethodAsync("delete", HttpMethod.DELETE);
}
private void AssertHttpMethodAsync(String path, HttpMethod method)
{
ManualResetEvent manualEvent = new ManualResetEvent(false);
Exception exception = null;
IClientHttpRequest request = this.CreateRequest("/methods/" + path, method);
request.Headers.ContentLength = 0; // TODO : post/put null
request.ExecuteAsync(null, delegate(ExecuteCompletedEventArgs args)
{
try
{
Assert.IsNull(args.Error, "Invalid response");
Assert.IsFalse(args.Cancelled, "Invalid response");
Assert.AreEqual(HttpStatusCode.OK, args.Response.StatusCode, "Invalid status code");
Assert.AreEqual(path, args.Response.StatusDescription, "Invalid status description");
}
catch (Exception ex)
{
exception = ex;
}
finally
{
manualEvent.Set();
}
});
manualEvent.WaitOne();
if (exception != null)
{
throw exception;
}
}
[Test]
public void CancelAsync()
{
ManualResetEvent manualEvent = new ManualResetEvent(false);
Exception exception = null;
IClientHttpRequest request = this.CreateRequest("/sleep/2", HttpMethod.GET);
request.ExecuteAsync(null, delegate(ExecuteCompletedEventArgs args)
{
try
{
Assert.IsTrue(args.Cancelled, "Invalid response");
WebException webEx = args.Error as WebException;
Assert.IsNotNull(webEx, "Invalid response exception");
Assert.AreEqual(WebExceptionStatus.RequestCanceled, webEx.Status, "Invalid response exception status");
}
catch (Exception ex)
{
exception = ex;
}
finally
{
manualEvent.Set();
}
});
request.CancelAsync();
manualEvent.WaitOne();
if (exception != null)
{
throw exception;
}
}
#endregion
#region Test service
[ServiceContract]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class TestService
{
[OperationContract]
[WebInvoke(UriTemplate = "echo", Method = "PUT")]
public Stream Echo(Stream message)
{
WebOperationContext context = WebOperationContext.Current;
foreach (string headerName in context.IncomingRequest.Headers)
{
context.OutgoingResponse.Headers[headerName] = context.IncomingRequest.Headers[headerName];
}
context.OutgoingResponse.StatusCode = HttpStatusCode.OK;
return message;
}
[OperationContract]
[WebGet(UriTemplate = "status/ok")]
public void StatusOk()
{
WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.OK;
WebOperationContext.Current.OutgoingResponse.StatusDescription = "Status OK";
}
[OperationContract]
[WebGet(UriTemplate = "status/notfound")]
public void StatusNotFound()
{
WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.NotFound;
WebOperationContext.Current.OutgoingResponse.StatusDescription = "Status NotFound";
}
[OperationContract]
[WebGet(UriTemplate = "methods/get")]
public void MethodsGet()
{
WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.OK;
WebOperationContext.Current.OutgoingResponse.StatusDescription = "get";
}
[OperationContract]
[WebInvoke(UriTemplate = "methods/delete", Method = "DELETE")]
public void MethodsDelete()
{
WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.OK;
WebOperationContext.Current.OutgoingResponse.StatusDescription = "delete";
}
[OperationContract]
[WebInvoke(UriTemplate = "methods/head", Method = "HEAD")]
public void MethodsHead()
{
WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.OK;
WebOperationContext.Current.OutgoingResponse.StatusDescription = "head";
}
[OperationContract]
[WebInvoke(UriTemplate = "methods/options", Method = "OPTIONS")]
public void MethodsOptions()
{
WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.OK;
WebOperationContext.Current.OutgoingResponse.StatusDescription = "options";
}
[OperationContract]
[WebInvoke(UriTemplate = "methods/post", Method = "POST")]
public void MethodsPost()
{
WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.OK;
WebOperationContext.Current.OutgoingResponse.StatusDescription = "post";
}
[OperationContract]
[WebInvoke(UriTemplate = "methods/put", Method = "PUT")]
public void MethodsPut()
{
WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.OK;
WebOperationContext.Current.OutgoingResponse.StatusDescription = "put";
}
[OperationContract]
[WebGet(UriTemplate = "sleep/{seconds}")]
public void Sleep(string seconds)
{
Thread.Sleep(TimeSpan.FromSeconds(Int32.Parse(seconds)));
WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.OK;
WebOperationContext.Current.OutgoingResponse.StatusDescription = "Status OK";
}
}
#endregion
}
}
#endif

View File

@@ -1,182 +0,0 @@
#if NET_3_5
#region License
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System;
using System.Net;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.ServiceModel.Security;
using System.IdentityModel.Tokens;
using System.IdentityModel.Selectors;
using NUnit.Framework;
namespace Spring.Http.Client
{
/// <summary>
/// Unit tests for the WebClientHttpRequestFactory class.
/// </summary>
/// <author>Bruno Baia</author>
[TestFixture]
public class WebClientHttpRequestFactoryIntegrationTests : AbstractClientHttpRequestFactoryIntegrationTests
{
private WebClientHttpRequestFactory webRequestFactory;
protected override IClientHttpRequestFactory CreateRequestFactory()
{
webRequestFactory = new WebClientHttpRequestFactory();
return webRequestFactory;
}
protected override void ConfigureWebServiceHost(WebServiceHost webServiceHost)
{
WebHttpBinding httpBinding1 = new WebHttpBinding();
httpBinding1.Security.Mode = WebHttpSecurityMode.TransportCredentialOnly;
httpBinding1.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
webServiceHost.AddServiceEndpoint(typeof(TestService), httpBinding1, "/basic");
WebHttpBinding httpBinding2 = new WebHttpBinding();
httpBinding2.Security.Mode = WebHttpSecurityMode.TransportCredentialOnly;
httpBinding2.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
webServiceHost.AddServiceEndpoint(typeof(TestService), httpBinding2, "/ntlm");
webServiceHost.Credentials.UserNameAuthentication.UserNamePasswordValidationMode = UserNamePasswordValidationMode.Custom;
webServiceHost.Credentials.UserNameAuthentication.CustomUserNamePasswordValidator = new CustomUserNamePasswordValidator();
}
[Test]
public void Timeout()
{
this.webRequestFactory.Timeout = 1000;
IClientHttpRequest request = this.CreateRequest("/sleep/2", HttpMethod.GET);
try
{
request.Execute();
Assert.Fail("Execute should failed !");
}
catch (Exception ex)
{
WebException webEx = ex as WebException;
Assert.IsNotNull(webEx, "Invalid response exception");
Assert.AreEqual(WebExceptionStatus.Timeout, webEx.Status, "Invalid response exception status");
}
}
[Test]
public void BasicAuthorizationKO()
{
IClientHttpRequest request = this.CreateRequest("/basic/echo", HttpMethod.PUT);
string authInfo = "bruno:password";
authInfo = Convert.ToBase64String(Encoding.UTF8.GetBytes(authInfo));
request.Headers["Authorization"] = "Basic " + authInfo;
request.Headers.ContentLength = 0;
using (IClientHttpResponse response = request.Execute())
{
Assert.AreEqual(HttpStatusCode.Forbidden, response.StatusCode, "Invalid status code");
}
}
[Test]
public void BasicAuthorizationOK()
{
IClientHttpRequest request = this.CreateRequest("/basic/echo", HttpMethod.PUT);
string authInfo = "login:password";
authInfo = Convert.ToBase64String(Encoding.UTF8.GetBytes(authInfo));
request.Headers["Authorization"] = "Basic " + authInfo;
request.Headers.ContentLength = 0;
using (IClientHttpResponse response = request.Execute())
{
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, "Invalid status code");
}
}
[Test]
public void NtlmAuthorizationKO()
{
IClientHttpRequest request = this.CreateRequest("/ntlm/echo", HttpMethod.PUT);
request.Headers.ContentLength = 0;
using (IClientHttpResponse response = request.Execute())
{
Assert.AreEqual(HttpStatusCode.Unauthorized, response.StatusCode, "Invalid status code");
}
}
[Test]
public void NtlmAuthorizationOK()
{
this.webRequestFactory.UseDefaultCredentials = true;
IClientHttpRequest request = this.CreateRequest("/ntlm/echo", HttpMethod.PUT);
request.Headers.ContentLength = 0;
using (IClientHttpResponse response = request.Execute())
{
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, "Invalid status code");
}
}
[Test]
public void SpecialHeaders() // related to HttpWebRequest implementation
{
IClientHttpRequest request = this.CreateRequest("/echo", HttpMethod.PUT);
request.Headers.Accept = new MediaType[] { MediaType.ALL };
request.Headers.ContentType = MediaType.TEXT_PLAIN;
request.Headers["Connection"] = "close";
request.Headers.ContentLength = 0;
#if NET_4_0
request.Headers.Date = DateTime.Now;
#endif
request.Headers["Expect"] = "bla";
request.Headers.IfModifiedSince = DateTime.Now;
request.Headers["Referer"] = "http://www.springframework.net/";
//request.Headers["Transfer-Encoding"] = "Identity";
request.Headers["User-Agent"] = "Unit tests";
using (IClientHttpResponse response = request.Execute())
{
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, "Invalid status code");
}
}
#region Test classes
public class CustomUserNamePasswordValidator : UserNamePasswordValidator
{
public override void Validate(string userName, string password)
{
if (userName == "login" && password == "password")
{
return;
}
throw new SecurityTokenException("Unknown username or incorrect password");
}
}
#endregion
}
}
#endif

View File

@@ -1,87 +0,0 @@
#region License
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using NUnit.Framework;
namespace Spring.Http.Converters
{
/// <summary>
/// Unit tests for the ByteArrayHttpMessageConverter class.
/// </summary>
/// <author>Arjen Poutsma</author>
/// <author>Bruno Baia (.NET)</author>
[TestFixture]
public class ByteArrayHttpMessageConverterTests
{
private ByteArrayHttpMessageConverter converter;
[SetUp]
public void SetUp()
{
converter = new ByteArrayHttpMessageConverter();
}
[Test]
public void CanRead()
{
Assert.IsTrue(converter.CanRead(typeof(byte[]), new MediaType("application", "octet-stream")));
Assert.IsTrue(converter.CanRead(typeof(byte[]), new MediaType("application", "xml")));
Assert.IsTrue(converter.CanRead(typeof(byte[]), MediaType.ALL));
Assert.IsFalse(converter.CanRead(typeof(string), new MediaType("application", "octet-stream")));
}
[Test]
public void CanWrite()
{
Assert.IsTrue(converter.CanWrite(typeof(byte[]), new MediaType("application", "octet-stream")));
Assert.IsTrue(converter.CanWrite(typeof(byte[]), new MediaType("application", "xml")));
Assert.IsTrue(converter.CanWrite(typeof(byte[]), MediaType.ALL));
Assert.IsFalse(converter.CanWrite(typeof(string), new MediaType("application", "octet-stream")));
}
[Test]
public void Read()
{
byte[] body = new byte[] { 0x1, 0x2 };
MockHttpInputMessage message = new MockHttpInputMessage(body);
message.Headers.ContentLength = body.Length;
byte[] result = converter.Read<byte[]>(message);
Assert.AreEqual(body.Length, result.Length, "Invalid result");
Assert.AreEqual(body[0], result[0], "Invalid result");
Assert.AreEqual(body[1], result[1], "Invalid result");
}
[Test]
public void Write()
{
byte[] body = new byte[] { 0x1, 0x2 };
MockHttpOutputMessage message = new MockHttpOutputMessage();
converter.Write(body, null, message);
Assert.AreEqual(body, message.GetBodyAsBytes(), "Invalid result");
Assert.AreEqual(new MediaType("application", "octet-stream"), message.Headers.ContentType, "Invalid content-type");
//Assert.AreEqual(2, message.Headers.ContentLength, "Invalid content-length");
}
}
}

View File

@@ -1,114 +0,0 @@
#if NET_3_5
#region License
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System;
using System.Text;
using System.Globalization;
using System.ServiceModel.Syndication;
using NUnit.Framework;
namespace Spring.Http.Converters.Feed
{
/// <summary>
/// Unit tests for the Atom10FeedHttpMessageConverter class.
/// </summary>
/// <author>Bruno Baia</author>
[TestFixture]
public class Atom10FeedHttpMessageConverterTests
{
private Atom10FeedHttpMessageConverter converter;
[SetUp]
public void SetUp()
{
converter = new Atom10FeedHttpMessageConverter();
}
[Test]
public void CanRead()
{
Assert.IsTrue(converter.CanRead(typeof(SyndicationFeed), new MediaType("application", "atom+xml")));
Assert.IsTrue(converter.CanRead(typeof(SyndicationItem), new MediaType("application", "atom+xml")));
Assert.IsTrue(converter.CanRead(typeof(SyndicationFeed), new MediaType("application", "xml")));
Assert.IsTrue(converter.CanRead(typeof(SyndicationFeed), new MediaType("text", "xml")));
Assert.IsFalse(converter.CanRead(typeof(string), new MediaType("application", "atom+xml")));
Assert.IsFalse(converter.CanRead(typeof(SyndicationFeed), new MediaType("text", "plain")));
}
[Test]
public void CanWrite()
{
Assert.IsTrue(converter.CanWrite(typeof(SyndicationFeed), new MediaType("application", "atom+xml")));
Assert.IsTrue(converter.CanWrite(typeof(SyndicationItem), new MediaType("application", "atom+xml")));
Assert.IsTrue(converter.CanWrite(typeof(SyndicationFeed), new MediaType("text", "xml")));
Assert.IsFalse(converter.CanWrite(typeof(string), new MediaType("application", "atom+xml")));
Assert.IsFalse(converter.CanWrite(typeof(SyndicationFeed), new MediaType("text", "plain")));
}
[Test]
public void Read()
{
DateTime now = DateTime.Now;
string body = String.Format("<feed xmlns=\"http://www.w3.org/2005/Atom\"><title type=\"text\">Test Feed</title><subtitle type=\"text\">This is a test feed</subtitle><id>Atom10FeedHttpMessageConverterTests.Write</id><rights type=\"text\">Copyright 2010</rights><updated>{0}</updated><author><name>Bruno Baïa</name><uri>http://www.springframework.net/bbaia</uri><email>bruno.baia@springframework.net</email></author><link rel=\"alternate\" href=\"http://www.springframework.net/Feed\" /></feed>",
now.ToString("yyyy-MM-ddTHH:mm:sszzz", CultureInfo.InvariantCulture));
MockHttpInputMessage message = new MockHttpInputMessage(body, Encoding.UTF8);
SyndicationFeed result = converter.Read<SyndicationFeed>(message);
Assert.IsNotNull(result, "Invalid result");
Assert.AreEqual("Atom10FeedHttpMessageConverterTests.Write", result.Id, "Invalid result");
Assert.AreEqual("Test Feed", result.Title.Text, "Invalid result");
Assert.AreEqual("This is a test feed", result.Description.Text, "Invalid result");
Assert.IsTrue(result.Links.Count == 1, "Invalid result");
Assert.AreEqual(new Uri("http://www.springframework.net/Feed"), result.Links[0].Uri, "Invalid result");
Assert.AreEqual("Copyright 2010", result.Copyright.Text, "Invalid result");
Assert.IsTrue(result.Authors.Count == 1, "Invalid result");
Assert.AreEqual("Bruno Baïa", result.Authors[0].Name, "Invalid result");
Assert.AreEqual("bruno.baia@springframework.net", result.Authors[0].Email, "Invalid result");
Assert.AreEqual("http://www.springframework.net/bbaia", result.Authors[0].Uri, "Invalid result");
}
[Test]
public void Write()
{
DateTime now = DateTime.Now;
string expectedBody = String.Format("<feed xmlns=\"http://www.w3.org/2005/Atom\"><title type=\"text\">Test Feed</title><subtitle type=\"text\">This is a test feed</subtitle><id>Atom10FeedHttpMessageConverterTests.Write</id><rights type=\"text\">Copyright 2010</rights><updated>{0}</updated><author><name>Bruno Baïa</name><uri>http://www.springframework.net/bbaia</uri><email>bruno.baia@springframework.net</email></author><link rel=\"alternate\" href=\"http://www.springframework.net/Feed\" /></feed>",
now.ToString("yyyy-MM-ddTHH:mm:sszzz", CultureInfo.InvariantCulture));
SyndicationFeed body = new SyndicationFeed("Test Feed", "This is a test feed", new Uri("http://www.springframework.net/Feed"), "Atom10FeedHttpMessageConverterTests.Write", now);
SyndicationPerson sp = new SyndicationPerson("bruno.baia@springframework.net", "Bruno Baïa", "http://www.springframework.net/bbaia");
body.Authors.Add(sp);
body.Copyright = new TextSyndicationContent("Copyright 2010");
MockHttpOutputMessage message = new MockHttpOutputMessage();
converter.Write(body, null, message);
Assert.AreEqual(expectedBody, message.GetBodyAsString(Encoding.UTF8), "Invalid result");
Assert.AreEqual(new MediaType("application", "atom+xml"), message.Headers.ContentType, "Invalid content-type");
//Assert.IsTrue(message.Headers.ContentLength > -1, "Invalid content-length");
}
}
}
#endif

View File

@@ -1,173 +0,0 @@
#if NET_3_5
#region License
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System;
using System.Net;
using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.ServiceModel.Syndication;
using Spring.Http.Rest;
using NUnit.Framework;
namespace Spring.Http.Converters.Feed
{
/// <summary>
/// Integration tests for the SyndicationFeed based IHttpMessageConverter class.
/// </summary>
/// <author>Bruno Baia</author>
[TestFixture]
public class FeedHttpMessageConverterIntegrationTests
{
#region Logging
private static readonly Common.Logging.ILog LOG = Common.Logging.LogManager.GetLogger(typeof(FeedHttpMessageConverterIntegrationTests));
#endregion
private WebServiceHost webServiceHost;
private string uri = "http://localhost:1337";
private RestTemplate template;
[SetUp]
public void SetUp()
{
template = new RestTemplate(uri);
template.MessageConverters = new List<IHttpMessageConverter>();
//template.MessageConverters.Add(new StringHttpMessageConverter()); // for debugging purpose
webServiceHost = new WebServiceHost(typeof(TestService), new Uri(uri));
webServiceHost.Open();
}
[TearDown]
public void TearDown()
{
webServiceHost.Close();
}
[Test]
public void Rss20GetForObject()
{
template.MessageConverters.Add(new Rss20FeedHttpMessageConverter());
SyndicationFeed result = template.GetForObject<SyndicationFeed>("feed");
Assert.IsNotNull(result, "Invalid content");
Assert.AreEqual("Test Feed", result.Title.Text, "Invalid content");
Assert.AreEqual("This is a test feed", result.Description.Text, "Invalid content");
}
[Test]
public void Rss20PostForMessage()
{
template.MessageConverters.Add(new Rss20FeedHttpMessageConverter());
SyndicationItem item = new SyndicationItem("Bruno's item", "Bruno's content", null);
HttpResponseMessage result = template.PostForMessage("feed/entry", item);
Assert.IsNull(result.Body, "Invalid content");
Assert.AreEqual(HttpStatusCode.Created, result.StatusCode, "Invalid status code");
Assert.AreEqual("Syndication item added with title 'Bruno's item'", result.StatusDescription, "Invalid status description");
}
[Test]
public void Atom10GetForObject()
{
template.MessageConverters.Add(new Atom10FeedHttpMessageConverter());
SyndicationFeed result = template.GetForObject<SyndicationFeed>("feed/?format=atom");
Assert.IsNotNull(result, "Invalid content");
Assert.AreEqual("Test Feed", result.Title.Text, "Invalid content");
Assert.AreEqual("This is a test feed", result.Description.Text, "Invalid content");
}
[Test]
public void Atom10PostForMessage()
{
template.MessageConverters.Add(new Atom10FeedHttpMessageConverter());
SyndicationItem item = new SyndicationItem("Bruno's item", "Bruno's content", null);
HttpResponseMessage result = template.PostForMessage("feed/entry", item);
Assert.IsNull(result.Body, "Invalid content");
Assert.AreEqual(HttpStatusCode.Created, result.StatusCode, "Invalid status code");
Assert.AreEqual("Syndication item added with title 'Bruno's item'", result.StatusDescription, "Invalid status description");
}
#region REST test service
[ServiceContract]
[ServiceKnownType(typeof(Atom10FeedFormatter))]
[ServiceKnownType(typeof(Rss20FeedFormatter))]
[ServiceKnownType(typeof(Atom10ItemFormatter))]
[ServiceKnownType(typeof(Rss20ItemFormatter))]
public class TestService
{
[OperationContract]
[WebGet(UriTemplate = "feed/", BodyStyle = WebMessageBodyStyle.Bare)]
public SyndicationFeedFormatter CreateFeed()
{
// Create a new Syndication Feed.
SyndicationFeed feed = new SyndicationFeed("Test Feed", "This is a test feed", null);
List<SyndicationItem> items = new List<SyndicationItem>();
// Create a new Syndication Item.
SyndicationItem item = new SyndicationItem("An item", "Item content", null);
items.Add(item);
feed.Items = items;
// Return ATOM or RSS based on uri
// rss -> http://localhost:1337/feed/
// atom -> http://localhost:1337/feed/?format=atom
string query = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters["format"];
SyndicationFeedFormatter formatter = null;
if (query == "atom")
{
formatter = new Atom10FeedFormatter(feed);
}
else
{
formatter = new Rss20FeedFormatter(feed);
}
return formatter;
}
[OperationContract]
[WebInvoke(UriTemplate = "feed/entry")]
public void AddEntry(SyndicationItemFormatter item)
{
WebOperationContext context = WebOperationContext.Current;
// Add entry
// ..
context.OutgoingResponse.StatusCode = HttpStatusCode.Created;
context.OutgoingResponse.StatusDescription = String.Format("Syndication item added with title '{0}'", item.Item.Title.Text);
}
}
#endregion
}
}
#endif

View File

@@ -1,113 +0,0 @@
#if NET_3_5
#region License
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System;
using System.Text;
using System.Globalization;
using System.ServiceModel.Syndication;
using NUnit.Framework;
namespace Spring.Http.Converters.Feed
{
/// <summary>
/// Unit tests for the Rss20FeedHttpMessageConverter class.
/// </summary>
/// <author>Bruno Baia</author>
[TestFixture]
public class Rss20FeedHttpMessageConverterTests
{
private Rss20FeedHttpMessageConverter converter;
[SetUp]
public void SetUp()
{
converter = new Rss20FeedHttpMessageConverter();
}
[Test]
public void CanRead()
{
Assert.IsTrue(converter.CanRead(typeof(SyndicationFeed), new MediaType("application", "rss+xml")));
Assert.IsTrue(converter.CanRead(typeof(SyndicationItem), new MediaType("application", "rss+xml")));
Assert.IsTrue(converter.CanRead(typeof(SyndicationFeed), new MediaType("application", "xml")));
Assert.IsTrue(converter.CanRead(typeof(SyndicationFeed), new MediaType("text", "xml")));
Assert.IsFalse(converter.CanRead(typeof(string), new MediaType("application", "rss+xml")));
Assert.IsFalse(converter.CanRead(typeof(SyndicationFeed), new MediaType("text", "plain")));
}
[Test]
public void CanWrite()
{
Assert.IsTrue(converter.CanWrite(typeof(SyndicationFeed), new MediaType("application", "rss+xml")));
Assert.IsTrue(converter.CanWrite(typeof(SyndicationItem), new MediaType("application", "rss+xml")));
Assert.IsTrue(converter.CanWrite(typeof(SyndicationFeed), new MediaType("application", "xml")));
Assert.IsTrue(converter.CanWrite(typeof(SyndicationFeed), new MediaType("text", "xml")));
Assert.IsFalse(converter.CanWrite(typeof(string), new MediaType("application", "rss+xml")));
Assert.IsFalse(converter.CanWrite(typeof(SyndicationFeed), new MediaType("text", "plain")));
}
[Test]
public void Read()
{
DateTime now = DateTime.Now;
string body = String.Format("<rss xmlns:a10=\"http://www.w3.org/2005/Atom\" version=\"2.0\"><channel><title>Test Feed</title><link>http://www.springframework.net/Feed</link><description>This is a test feed</description><copyright>Copyright 2010</copyright><managingEditor>bruno.baia@springframework.net</managingEditor><lastBuildDate>{0}</lastBuildDate><a10:id>Atom10FeedHttpMessageConverterTests.Write</a10:id></channel></rss>",
now.ToString("ddd, dd MMM yyyy HH:mm:ss zzz", CultureInfo.InvariantCulture).Remove(29, 1));
MockHttpInputMessage message = new MockHttpInputMessage(body, Encoding.UTF8);
SyndicationFeed result = converter.Read<SyndicationFeed>(message);
Assert.IsNotNull(result, "Invalid result");
Assert.AreEqual("Atom10FeedHttpMessageConverterTests.Write", result.Id, "Invalid result");
Assert.AreEqual("Test Feed", result.Title.Text, "Invalid result");
Assert.AreEqual("This is a test feed", result.Description.Text, "Invalid result");
Assert.IsTrue(result.Links.Count == 1, "Invalid result");
Assert.AreEqual(new Uri("http://www.springframework.net/Feed"), result.Links[0].Uri, "Invalid result");
Assert.AreEqual("Copyright 2010", result.Copyright.Text, "Invalid result");
Assert.IsTrue(result.Authors.Count == 1, "Invalid result");
Assert.AreEqual("bruno.baia@springframework.net", result.Authors[0].Email, "Invalid result");
}
[Test]
public void Write()
{
DateTime now = DateTime.Now;
string expectedBody = String.Format("<rss xmlns:a10=\"http://www.w3.org/2005/Atom\" version=\"2.0\"><channel><title>Test Feed</title><link>http://www.springframework.net/Feed</link><description>This is a test feed</description><copyright>Copyright 2010</copyright><managingEditor>bruno.baia@springframework.net</managingEditor><lastBuildDate>{0}</lastBuildDate><a10:id>Atom10FeedHttpMessageConverterTests.Write</a10:id></channel></rss>",
now.ToString("ddd, dd MMM yyyy HH:mm:ss zzz", CultureInfo.InvariantCulture).Remove(29, 1));
SyndicationFeed body = new SyndicationFeed("Test Feed", "This is a test feed", new Uri("http://www.springframework.net/Feed"), "Atom10FeedHttpMessageConverterTests.Write", now);
SyndicationPerson sp = new SyndicationPerson("bruno.baia@springframework.net", "Bruno Baïa", "http://www.springframework.net/bbaia");
body.Authors.Add(sp);
body.Copyright = new TextSyndicationContent("Copyright 2010");
MockHttpOutputMessage message = new MockHttpOutputMessage();
converter.Write(body, null, message);
Assert.AreEqual(expectedBody, message.GetBodyAsString(Encoding.UTF8), "Invalid result");
Assert.AreEqual(new MediaType("application", "rss+xml"), message.Headers.ContentType, "Invalid content-type");
//Assert.IsTrue(message.Headers.ContentLength > -1, "Invalid content-length");
}
}
}
#endif

View File

@@ -1,109 +0,0 @@
#region License
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System.IO;
using NUnit.Framework;
namespace Spring.Http.Converters
{
/// <summary>
/// Unit tests for the FileInfoHttpMessageConverter class.
/// </summary>
/// <author>Bruno Baia</author>
[TestFixture]
public class FileInfoHttpMessageConverterTests
{
private FileInfoHttpMessageConverter converter;
[SetUp]
public void SetUp()
{
converter = new FileInfoHttpMessageConverter();
}
[Test]
public void CanRead()
{
Assert.IsFalse(converter.CanRead(typeof(FileInfo), MediaType.ALL));
}
[Test]
public void CanWrite()
{
Assert.IsTrue(converter.CanWrite(typeof(FileInfo), new MediaType("application", "octet-stream")));
Assert.IsTrue(converter.CanWrite(typeof(FileInfo), new MediaType("application", "xml")));
Assert.IsTrue(converter.CanWrite(typeof(FileInfo), MediaType.ALL));
Assert.IsFalse(converter.CanWrite(typeof(string), new MediaType("application", "octet-stream")));
}
//[Test]
//public void Write()
//{
// FileInfo body = new FileInfo(@"C:\File.txt");
// MockHttpOutputMessage message = new MockHttpOutputMessage();
// converter.Write(body, null, message);
// Assert.AreEqual(body, message.GetBodyAsBytes(), "Invalid result");
// Assert.AreEqual(new MediaType("text", "plain"), message.Headers.ContentType, "Invalid content-type");
//}
[Test]
public void WriteWithUnknownExtension()
{
FileInfo body = new FileInfo(@"C:\Dummy.unknown");
MockHttpOutputMessage message = new MockHttpOutputMessage();
converter.Write(body, null, message);
//Assert.AreEqual(body, message.GetBodyAsBytes(), "Invalid result");
Assert.AreEqual(new MediaType("application", "octet-stream"), message.Headers.ContentType, "Invalid content-type");
}
[Test]
public void WriteWithKnownExtension()
{
FileInfo body = new FileInfo(@"C:\Dummy.txt");
MockHttpOutputMessage message = new MockHttpOutputMessage();
converter.Write(body, null, message);
Assert.AreEqual(new MediaType("text", "plain"), message.Headers.ContentType, "Invalid content-type");
}
[Test]
public void WriteWithCustomExtension()
{
FileInfo body = new FileInfo(@"C:\Dummy.myext");
MockHttpOutputMessage message = new MockHttpOutputMessage();
converter.MimeMapping.Add(".myext", "spring/custom");
converter.Write(body, null, message);
Assert.AreEqual(new MediaType("spring", "custom"), message.Headers.ContentType, "Invalid content-type");
}
}
}

View File

@@ -1,139 +0,0 @@
#region License
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Collections.Specialized;
using NUnit.Framework;
namespace Spring.Http.Converters
{
/// <summary>
/// Unit tests for the FormHttpMessageConverter class.
/// </summary>
/// <author>Arjen Poutsma</author>
/// <author>Bruno Baia (.NET)</author>
[TestFixture]
public class FormHttpMessageConverterTests
{
private FormHttpMessageConverter converter;
[SetUp]
public void SetUp()
{
converter = new FormHttpMessageConverter();
}
[Test]
public void CanRead()
{
Assert.IsTrue(converter.CanRead(typeof(NameValueCollection), new MediaType("application", "x-www-form-urlencoded")));
Assert.IsFalse(converter.CanRead(typeof(NameValueCollection), new MediaType("application", "xml")));
Assert.IsFalse(converter.CanRead(typeof(string), new MediaType("application", "x-www-form-urlencoded")));
Assert.IsFalse(converter.CanRead(typeof(IDictionary<string, object>), new MediaType("multipart","form-data")));
}
[Test]
public void CanWrite()
{
Assert.IsTrue(converter.CanWrite(typeof(NameValueCollection), new MediaType("application", "x-www-form-urlencoded")));
Assert.IsFalse(converter.CanWrite(typeof(NameValueCollection), new MediaType("application", "xml")));
Assert.IsFalse(converter.CanWrite(typeof(string), new MediaType("application", "x-www-form-urlencoded")));
Assert.IsTrue(converter.CanWrite(typeof(IDictionary<string, object>), new MediaType("multipart", "form-data")));
Assert.IsFalse(converter.CanWrite(typeof(IDictionary<string, object>), new MediaType("application", "xml")));
Assert.IsFalse(converter.CanWrite(typeof(string), new MediaType("multipart", "form-data")));
}
[Test]
public void ReadForm()
{
String body = "name+1=value+1&name+2=value+2%2B1&name+2=value+2%2B2&name+3";
string charSet = "ISO-8859-1";
Encoding charSetEncoding = Encoding.GetEncoding(charSet);
MediaType mediaType = new MediaType("application", "x-www-form-urlencoded", charSet);
MockHttpInputMessage message = new MockHttpInputMessage(body, charSetEncoding);
message.Headers.ContentType = mediaType;
NameValueCollection result = converter.Read<NameValueCollection>(message);
Assert.AreEqual(3, result.Count, "Invalid result");
Assert.AreEqual(1, result.GetValues(0).Length, "Invalid result");
Assert.AreEqual("value 1", result.GetValues(0)[0], "Invalid result");
Assert.AreEqual(2, result.GetValues("name 2").Length, "Invalid result");
Assert.AreEqual("value 2+1", result.GetValues("name 2")[0], "Invalid result");
Assert.AreEqual("value 2+2", result.GetValues("name 2")[1], "Invalid result");
Assert.IsNull(result["name 3"], "Invalid result");
}
[Test]
public void WriteForm()
{
string expectedBody = "name+1=value+1&name+2=value+2%2b1&name+2=value+2%2b2&name+3";
NameValueCollection body = new NameValueCollection();
body.Add("name 1", "value 1");
body.Add("name 2", "value 2+1");
body.Add("name 2", "value 2+2");
body.Add("name 3", null);
string charSet = "ISO-8859-1";
Encoding charSetEncoding = Encoding.GetEncoding(charSet);
MockHttpOutputMessage message = new MockHttpOutputMessage();
converter.Write(body, MediaType.APPLICATION_FORM_URLENCODED, message);
Assert.AreEqual(expectedBody, message.GetBodyAsString(charSetEncoding), "Invalid result");
Assert.AreEqual(new MediaType("application", "x-www-form-urlencoded"), message.Headers.ContentType, "Invalid content-type");
//Assert.AreEqual(charSetEncoding.GetBytes(expectedBody).Length, message.Headers.ContentLength, "Invalid content-length");
}
[Test]
[Ignore] //TODO: relative path (needs IResource ?)
public void WriteMultipart()
{
IDictionary<string, object> parts = new Dictionary<string, object>();
parts.Add("name 1", "value 1");
parts.Add("name 2", "value 2+1");
HttpEntity entity = new HttpEntity("<root><child/></root>");
entity.Headers.ContentType = MediaType.TEXT_XML;
parts.Add("xml", entity);
parts.Add("logo", new FileInfo(@"C:\Users\Bruno\Pictures\Hero\downloadfile.jpeg"));
MockHttpOutputMessage message = new MockHttpOutputMessage();
converter.Write(parts, MediaType.MULTIPART_FORM_DATA, message);
MediaType contentType = message.Headers.ContentType;
Assert.IsNotNull(contentType, "Invalid content-type");
Assert.AreEqual("multipart", contentType.Type, "Invalid content-type");
Assert.AreEqual("form-data", contentType.Subtype, "Invalid content-type");
string boundary = contentType.GetParameter("boundary");
Assert.IsNotNull(boundary, "Invalid content-type");
string result = message.GetBodyAsString(Encoding.UTF8);
Assert.IsTrue(result.Contains("--" + boundary + "\r\nContent-Disposition: form-data; name=\"name 1\"\r\nContent-Type: text/plain;charset=ISO-8859-1\r\n\r\nvalue 1\r\n"), "Invalid content-disposition");
Assert.IsTrue(result.Contains("--" + boundary + "\r\nContent-Disposition: form-data; name=\"name 2\"\r\nContent-Type: text/plain;charset=ISO-8859-1\r\n\r\nvalue 2+1\r\n"), "Invalid content-disposition");
Assert.IsTrue(result.Contains("--" + boundary + "\r\nContent-Disposition: form-data; name=\"xml\"\r\nContent-Type: text/xml\r\n\r\n<root><child/></root>\r\n"), "Invalid content-disposition");
Assert.IsTrue(result.Contains("--" + boundary + "\r\nContent-Disposition: form-data; name=\"logo\"; filename=\"C:\\Users\\Bruno\\Pictures\\Hero\\downloadfile.jpeg\"\r\nContent-Type: image/jpeg\r\n\r\n"), "Invalid content-disposition");
}
}
}

View File

@@ -1,194 +0,0 @@
#if NET_3_5
#region License
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System;
using System.Net;
using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Runtime.Serialization;
using Spring.Http.Rest;
using NUnit.Framework;
namespace Spring.Http.Converters.Json
{
/// <summary>
/// Integration tests for the JsonHttpMessageConverter class.
/// </summary>
/// <author>Bruno Baia</author>
[TestFixture]
public class JsonHttpMessageConverterIntegrationTests
{
#region Logging
private static readonly Common.Logging.ILog LOG = Common.Logging.LogManager.GetLogger(typeof(JsonHttpMessageConverterIntegrationTests));
#endregion
private WebServiceHost webServiceHost;
private string uri = "http://localhost:1337";
private RestTemplate template;
private MediaType contentType;
[SetUp]
public void SetUp()
{
template = new RestTemplate(uri);
template.MessageConverters = new List<IHttpMessageConverter>();
contentType = new MediaType("application", "json");
webServiceHost = new WebServiceHost(typeof(TestService), new Uri(uri));
webServiceHost.Open();
}
[TearDown]
public void TearDown()
{
webServiceHost.Close();
}
[Test]
public void GetForJson()
{
template.MessageConverters.Add(new StringHttpMessageConverter());
string resultAsString = template.GetForObject<string>("user/{id}", 1);
Assert.AreEqual("{\"ID\":\"1\",\"Name\":\"Bruno Baïa\"}", resultAsString, "Invalid content");
}
[Test]
public void GetForObject()
{
template.MessageConverters.Add(new JsonHttpMessageConverter());
User result = template.GetForObject<User>("user/{id}", 1);
Assert.IsNotNull(result, "Invalid content");
Assert.AreEqual("1", result.ID, "Invalid content");
Assert.AreEqual("Bruno Baïa", result.Name, "Invalid content");
}
[Test]
public void PostJsonForMessage()
{
template.MessageConverters.Add(new StringHttpMessageConverter());
HttpEntity entity = new HttpEntity("{\"Name\":\"Lisa Baia\"}");
entity.Headers.ContentType = MediaType.APPLICATION_JSON;
HttpResponseMessage result = template.PostForMessage("user", entity);
Assert.IsNull(result.Body, "Invalid content");
Assert.AreEqual(new Uri(new Uri(uri), "/user/3"), result.Headers.Location, "Invalid location");
Assert.AreEqual(HttpStatusCode.Created, result.StatusCode, "Invalid status code");
Assert.AreEqual("User id '3' created with 'Lisa Baia'", result.StatusDescription, "Invalid status description");
}
[Test]
public void PostObjectForMessage()
{
template.MessageConverters.Add(new JsonHttpMessageConverter());
User user = new User() { Name = "Lisa Baia" };
HttpResponseMessage result = template.PostForMessage("user", user);
Assert.IsNull(result.Body, "Invalid content");
Assert.AreEqual(new Uri(new Uri(uri), "/user/3"), result.Headers.Location, "Invalid location");
Assert.AreEqual(HttpStatusCode.Created, result.StatusCode, "Invalid status code");
Assert.AreEqual("User id '3' created with 'Lisa Baia'", result.StatusDescription, "Invalid status description");
}
#region REST test service
[DataContract]
public class User
{
[DataMember]
public string ID { get; set; }
[DataMember]
public string Name { get; set; }
}
[ServiceContract]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class TestService
{
private IList<User> users;
public TestService()
{
users = new List<User>();
users.Add(new User() { ID = "1", Name = "Bruno Baïa" });
users.Add(new User() { ID = "2", Name = "Marie Baia" });
}
[OperationContract]
[WebGet(UriTemplate = "user/{id}", ResponseFormat = WebMessageFormat.Json)]
public User GetUser(string id)
{
WebOperationContext context = WebOperationContext.Current;
foreach (User user in this.users)
{
if (user.ID.Equals(id, StringComparison.InvariantCultureIgnoreCase))
{
return user;
}
}
context.OutgoingResponse.SetStatusAsNotFound(String.Format("User with id '{0}' not found", id));
return null;
}
[OperationContract]
[WebInvoke(UriTemplate = "user", Method = "POST", RequestFormat = WebMessageFormat.Json)]
public void Create(User user)
{
WebOperationContext context = WebOperationContext.Current;
UriTemplateMatch match = context.IncomingRequest.UriTemplateMatch;
UriTemplate template = new UriTemplate("/user/{id}");
MediaType mediaType = MediaType.Parse(context.IncomingRequest.ContentType);
if (!String.IsNullOrEmpty(user.ID))
{
context.OutgoingResponse.StatusCode = HttpStatusCode.BadRequest;
context.OutgoingResponse.StatusDescription = String.Format("User id '{0}' already exists", user.ID);
return;
}
user.ID = (users.Count + 1).ToString(); // generate new ID
users.Add(user);
Uri uri = template.BindByPosition(match.BaseUri, user.ID);
context.OutgoingResponse.SetStatusAsCreated(uri);
context.OutgoingResponse.StatusDescription = String.Format("User id '{0}' created with '{1}'", user.ID, user.Name);
}
}
#endregion
}
}
#endif

View File

@@ -1,107 +0,0 @@
#if NET_3_5
#region License
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System.Text;
using NUnit.Framework;
namespace Spring.Http.Converters.Json
{
/// <summary>
/// Unit tests for the JsonHttpMessageConverter class.
/// </summary>
/// <author>Bruno Baia</author>
[TestFixture]
public class JsonHttpMessageConverterTests
{
private JsonHttpMessageConverter converter;
[SetUp]
public void SetUp()
{
converter = new JsonHttpMessageConverter();
}
[Test]
public void CanRead()
{
Assert.IsTrue(converter.CanRead(typeof(CustomClass), new MediaType("application", "json")));
Assert.IsFalse(converter.CanRead(typeof(CustomClass), new MediaType("text", "xml")));
}
[Test]
public void CanWrite()
{
Assert.IsTrue(converter.CanWrite(typeof(CustomClass), new MediaType("application", "json")));
Assert.IsFalse(converter.CanWrite(typeof(CustomClass), new MediaType("text", "xml")));
}
[Test]
public void Read()
{
string body = "{\"ID\":\"1\",\"Name\":\"Bruno Baïa\"}";
MockHttpInputMessage message = new MockHttpInputMessage(body, Encoding.UTF8);
CustomClass result = converter.Read<CustomClass>(message);
Assert.IsNotNull(result, "Invalid result");
Assert.AreEqual("1", result.ID, "Invalid result");
Assert.AreEqual("Bruno Baïa", result.Name, "Invalid result");
}
[Test]
public void Write()
{
string expectedBody = "{\"ID\":\"1\",\"Name\":\"Bruno Baïa\"}";
CustomClass body = new CustomClass("1", "Bruno Baïa");
MockHttpOutputMessage message = new MockHttpOutputMessage();
converter.Write(body, null, message);
Assert.AreEqual(expectedBody, message.GetBodyAsString(Encoding.UTF8), "Invalid result");
Assert.AreEqual(new MediaType("application", "json"), message.Headers.ContentType, "Invalid content-type");
//Assert.IsTrue(message.Headers.ContentLength > -1, "Invalid content-length");
}
#region Test classes
public class CustomClass
{
public string ID { get; set; }
public string Name { get; set; }
public CustomClass()
{
}
public CustomClass(string id, string name)
{
this.ID = id;
this.Name = name;
}
}
#endregion
}
}
#endif

View File

@@ -1,110 +0,0 @@
#region License
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System.Text;
using NUnit.Framework;
namespace Spring.Http.Converters
{
/// <summary>
/// Unit tests for the StringHttpMessageConverter class.
/// </summary>
/// <author>Arjen Poutsma</author>
/// <author>Bruno Baia (.NET)</author>
[TestFixture]
public class StringHttpMessageConverterTests
{
private StringHttpMessageConverter converter;
[SetUp]
public void SetUp()
{
converter = new StringHttpMessageConverter();
}
[Test]
public void CanRead()
{
Assert.IsTrue(converter.CanRead(typeof(string), new MediaType("text", "plain")));
Assert.IsTrue(converter.CanRead(typeof(string), MediaType.ALL));
Assert.IsTrue(converter.CanRead(typeof(string), new MediaType("application", "xml")));
Assert.IsFalse(converter.CanRead(typeof(int[]), new MediaType("text", "plain")));
}
[Test]
public void CanWrite()
{
Assert.IsTrue(converter.CanWrite(typeof(string), new MediaType("text", "plain")));
Assert.IsTrue(converter.CanWrite(typeof(string), MediaType.ALL));
Assert.IsTrue(converter.CanWrite(typeof(string), new MediaType("application", "xml")));
Assert.IsFalse(converter.CanWrite(typeof(int[]), new MediaType("text", "plain")));
}
[Test]
public void Read()
{
string body = "Hello Bruno Baïa";
string charSet = "utf-8";
Encoding charSetEncoding = Encoding.GetEncoding(charSet);
MediaType mediaType = new MediaType("text", "plain", charSet);
MockHttpInputMessage message = new MockHttpInputMessage(body, charSetEncoding);
message.Headers.ContentType = mediaType;
string result = converter.Read<string>(message);
Assert.AreEqual(body, result, "Invalid result");
}
[Test]
public void WriteDefaultCharset()
{
string body = "H\u00e9llo W\u00f6rld";
string charSet = "ISO-8859-1";
Encoding charSetEncoding = Encoding.GetEncoding(charSet);
MediaType mediaType = new MediaType("text", "plain", charSet);
MockHttpOutputMessage message = new MockHttpOutputMessage();
converter.Write(body, null, message);
Assert.AreEqual(body, message.GetBodyAsString(charSetEncoding), "Invalid result");
Assert.AreEqual(mediaType, message.Headers.ContentType, "Invalid content-type");
//Assert.AreEqual(charSetEncoding.GetBytes(body).Length, message.Headers.ContentLength, "Invalid content-length");
}
[Test]
public void WriteUTF8()
{
string body = "H\u00e9llo W\u00f6rld";
string charSet = "UTF-8";
Encoding charSetEncoding = Encoding.GetEncoding(charSet);
MediaType mediaType = new MediaType("text", "plain", charSet);
MockHttpOutputMessage message = new MockHttpOutputMessage();
converter.Write(body, mediaType, message);
Assert.AreEqual(body, message.GetBodyAsString(charSetEncoding), "Invalid result");
Assert.AreEqual(mediaType, message.Headers.ContentType, "Invalid content-type");
//Assert.AreEqual(charSetEncoding.GetBytes(body).Length, message.Headers.ContentLength, "Invalid content-length");
}
}
}

View File

@@ -1,132 +0,0 @@
#if NET_3_0
#region License
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System.Text;
using System.Runtime.Serialization;
using System.Collections.Generic;
using NUnit.Framework;
namespace Spring.Http.Converters.Xml
{
/// <summary>
/// Unit tests for the DataContractHttpMessageConverter class.
/// </summary>
/// <author>Bruno Baia</author>
[TestFixture]
public class DataContractHttpMessageConverterTests
{
private DataContractHttpMessageConverter converter;
[SetUp]
public void SetUp()
{
converter = new DataContractHttpMessageConverter();
}
[Test]
public void CanRead()
{
Assert.IsTrue(converter.CanRead(typeof(DataContractClass), new MediaType("application", "xml")));
Assert.IsTrue(converter.CanRead(typeof(DataContractClass), new MediaType("text", "xml")));
Assert.IsTrue(converter.CanRead(typeof(DataContractClass), new MediaType("application", "soap+xml"))); // application/*+xml
Assert.IsFalse(converter.CanRead(typeof(DataContractClass), new MediaType("text", "plain")));
Assert.IsFalse(converter.CanRead(typeof(NonDataContractClass), new MediaType("application", "xml")));
Assert.IsTrue(converter.CanRead(typeof(CollectionDataContractClass), new MediaType("application", "xml")));
}
[Test]
public void CanWrite()
{
Assert.IsTrue(converter.CanWrite(typeof(DataContractClass), new MediaType("application", "xml")));
Assert.IsTrue(converter.CanWrite(typeof(DataContractClass), new MediaType("text", "xml")));
Assert.IsTrue(converter.CanWrite(typeof(DataContractClass), new MediaType("application", "soap+xml"))); // application/*+xml
Assert.IsFalse(converter.CanWrite(typeof(DataContractClass), new MediaType("text", "plain")));
Assert.IsFalse(converter.CanWrite(typeof(NonDataContractClass), new MediaType("application", "xml")));
Assert.IsTrue(converter.CanWrite(typeof(CollectionDataContractClass), new MediaType("application", "xml")));
}
[Test]
public void Read()
{
string body = @"<?xml version='1.0' encoding='UTF-8' ?>
<DataContractHttpMessageConverterTests.DataContractClass xmlns='http://schemas.datacontract.org/2004/07/Spring.Http.Converters.Xml' xmlns:i='http://www.w3.org/2001/XMLSchema-instance'>
<ID>1</ID><Name>Bruno Baïa</Name>
</DataContractHttpMessageConverterTests.DataContractClass>";
MockHttpInputMessage message = new MockHttpInputMessage(body, Encoding.UTF8);
DataContractClass result = converter.Read<DataContractClass>(message);
Assert.IsNotNull(result, "Invalid result");
Assert.AreEqual("1", result.ID, "Invalid result");
Assert.AreEqual("Bruno Baïa", result.Name, "Invalid result");
}
[Test]
public void Write()
{
string expectedBody = "<DataContractHttpMessageConverterTests.DataContractClass xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://schemas.datacontract.org/2004/07/Spring.Http.Converters.Xml\"><ID>1</ID><Name>Bruno Baïa</Name></DataContractHttpMessageConverterTests.DataContractClass>";
DataContractClass body = new DataContractClass("1", "Bruno Baïa");
MockHttpOutputMessage message = new MockHttpOutputMessage();
converter.Write(body, null, message);
Assert.AreEqual(expectedBody, message.GetBodyAsString(Encoding.UTF8), "Invalid result");
Assert.AreEqual(new MediaType("application", "xml"), message.Headers.ContentType, "Invalid content-type");
//Assert.IsTrue(message.Headers.ContentLength > -1, "Invalid content-length");
}
#region Test classes
[DataContract]
public class DataContractClass
{
[DataMember]
public string ID { get; set; }
[DataMember]
public string Name { get; set; }
public DataContractClass(string id, string name)
{
this.ID = id;
this.Name = name;
}
}
[CollectionDataContract]
public class CollectionDataContractClass : List<string>
{
public CollectionDataContractClass()
: base()
{
}
}
public class NonDataContractClass
{
}
#endregion
}
}
#endif

View File

@@ -1,102 +0,0 @@
#if NET_3_5
#region License
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System;
using System.Text;
using System.Linq;
using System.Xml.Linq;
using NUnit.Framework;
namespace Spring.Http.Converters.Xml
{
/// <summary>
/// Unit tests for the XElementHttpMessageConverter class.
/// </summary>
/// <author>Bruno Baia</author>
[TestFixture]
public class XElementHttpMessageConverterTests
{
private XElementHttpMessageConverter converter;
[SetUp]
public void SetUp()
{
converter = new XElementHttpMessageConverter();
}
[Test]
public void CanRead()
{
Assert.IsTrue(converter.CanRead(typeof(XElement), new MediaType("application", "xml")));
Assert.IsTrue(converter.CanRead(typeof(XElement), new MediaType("text", "xml")));
Assert.IsTrue(converter.CanRead(typeof(XElement), new MediaType("application", "soap+xml"))); // application/*+xml
Assert.IsFalse(converter.CanRead(typeof(XElement), new MediaType("text", "plain")));
Assert.IsFalse(converter.CanRead(typeof(String), new MediaType("application", "xml")));
}
[Test]
public void CanWrite()
{
Assert.IsTrue(converter.CanWrite(typeof(XElement), new MediaType("application", "xml")));
Assert.IsTrue(converter.CanWrite(typeof(XElement), new MediaType("text", "xml")));
Assert.IsTrue(converter.CanWrite(typeof(XElement), new MediaType("application", "soap+xml"))); // application/*+xml
Assert.IsFalse(converter.CanWrite(typeof(XElement), new MediaType("text", "plain")));
Assert.IsFalse(converter.CanWrite(typeof(String), new MediaType("application", "xml")));
}
[Test]
public void Read()
{
string body = "<?xml version='1.0' encoding='UTF-8' ?><Root><TestElement testAttribute='value'/><TestElement testAttribute='novalue'/></Root>";
MockHttpInputMessage message = new MockHttpInputMessage(body, Encoding.UTF8);
XElement result = converter.Read<XElement>(message);
Assert.IsNotNull(result, "Invalid result");
//XElement xResult = result.Elements()
// .Where(x => x.Name == "TestElement" && x.Attribute("testAttribute").Value == "value")
// .Single();
XElement xResult = (from el in result.Elements()
where el.Name == "TestElement" && el.Attribute("testAttribute").Value == "value"
select el)
.Single();
Assert.IsNotNull(xResult, "Invalid result");
}
[Test]
public void Write()
{
XElement body = new XElement("Root",
new XElement("TestElement", 1),
new XElement("TestElement", 2));
MockHttpOutputMessage message = new MockHttpOutputMessage();
converter.Write(body, null, message);
Assert.AreEqual(body.ToString(SaveOptions.DisableFormatting), message.GetBodyAsString(Encoding.UTF8), "Invalid result");
Assert.AreEqual(new MediaType("application", "xml"), message.Headers.ContentType, "Invalid content-type");
//Assert.IsTrue(message.Headers.ContentLength > -1, "Invalid content-length");
}
}
}
#endif

View File

@@ -1,95 +0,0 @@
#region License
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System;
using System.Text;
using System.Xml;
using NUnit.Framework;
namespace Spring.Http.Converters.Xml
{
/// <summary>
/// Unit tests for the XmlDocumentHttpMessageConverter class.
/// </summary>
/// <author>Bruno Baia</author>
[TestFixture]
public class XmlDocumentHttpMessageConverterTests
{
private XmlDocumentHttpMessageConverter converter;
[SetUp]
public void SetUp()
{
converter = new XmlDocumentHttpMessageConverter();
}
[Test]
public void CanRead()
{
Assert.IsTrue(converter.CanRead(typeof(XmlDocument), new MediaType("application", "xml")));
Assert.IsTrue(converter.CanRead(typeof(XmlDocument), new MediaType("text", "xml")));
Assert.IsTrue(converter.CanRead(typeof(XmlDocument), new MediaType("application", "soap+xml"))); // application/*+xml
Assert.IsFalse(converter.CanRead(typeof(XmlDocument), new MediaType("text", "plain")));
Assert.IsFalse(converter.CanRead(typeof(String), new MediaType("application", "xml")));
}
[Test]
public void CanWrite()
{
Assert.IsTrue(converter.CanWrite(typeof(XmlDocument), new MediaType("application", "xml")));
Assert.IsTrue(converter.CanWrite(typeof(XmlDocument), new MediaType("text", "xml")));
Assert.IsTrue(converter.CanWrite(typeof(XmlDocument), new MediaType("application", "soap+xml"))); // application/*+xml
Assert.IsFalse(converter.CanWrite(typeof(XmlDocument), new MediaType("text", "plain")));
Assert.IsFalse(converter.CanWrite(typeof(String), new MediaType("application", "xml")));
}
[Test]
public void Read()
{
string body = "<TestElement testAttribute='value' />";
MockHttpInputMessage message = new MockHttpInputMessage(body, Encoding.UTF8);
XmlDocument result = converter.Read<XmlDocument>(message);
Assert.IsNotNull(result, "Invalid result");
XmlNode xmlNodeResult = result.SelectSingleNode("//TestElement");
Assert.IsNotNull(xmlNodeResult, "Invalid result");
Assert.AreEqual("TestElement", xmlNodeResult.LocalName, "Invalid result");
Assert.IsNotNull(xmlNodeResult.Attributes["testAttribute"], "Invalid result");
Assert.AreEqual("value", xmlNodeResult.Attributes["testAttribute"].Value, "Invalid result");
}
[Test]
public void Write()
{
XmlDocument body = new XmlDocument();
body.LoadXml("<TestElement testAttribute='value' />");
MockHttpOutputMessage message = new MockHttpOutputMessage();
converter.Write(body, null, message);
Assert.AreEqual(body.OuterXml, message.GetBodyAsString(Encoding.UTF8), "Invalid result");
Assert.AreEqual(new MediaType("application", "xml"), message.Headers.ContentType, "Invalid content-type");
//Assert.IsTrue(message.Headers.ContentLength > -1, "Invalid content-length");
}
}
}

View File

@@ -1,244 +0,0 @@
#if NET_3_5
#region License
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System;
using System.Net;
using System.Xml.Linq;
using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Runtime.Serialization;
using Spring.Http.Rest;
using NUnit.Framework;
namespace Spring.Http.Converters.Xml
{
/// <summary>
/// Integration tests for the Xml based IHttpMessageConverter class.
/// </summary>
/// <author>Bruno Baia</author>
[TestFixture]
public class XmlHttpMessageConverterIntegrationTests
{
#region Logging
private static readonly Common.Logging.ILog LOG = Common.Logging.LogManager.GetLogger(typeof(XmlHttpMessageConverterIntegrationTests));
#endregion
private WebServiceHost webServiceHost;
private string uri = "http://localhost:1337";
private RestTemplate template;
[SetUp]
public void SetUp()
{
template = new RestTemplate(uri);
template.MessageConverters = new List<IHttpMessageConverter>();
//template.MessageConverters.Add(new StringHttpMessageConverter()); // for debugging purpose
webServiceHost = new WebServiceHost(typeof(TestService), new Uri(uri));
webServiceHost.Open();
}
[TearDown]
public void TearDown()
{
webServiceHost.Close();
}
[Test]
public void DataContractGetForObject()
{
template.MessageConverters.Add(new DataContractHttpMessageConverter());
User result = template.GetForObject<User>("user/dc/{id}", "1");
Assert.IsNotNull(result, "Invalid content");
Assert.AreEqual("1", result.ID, "Invalid content");
Assert.AreEqual("Bruno Baïa", result.Name, "Invalid content");
}
[Test]
public void DataContractPostForMessage()
{
template.MessageConverters.Add(new DataContractHttpMessageConverter());
User user = new User() { Name = "Lisa Baia" };
HttpResponseMessage result = template.PostForMessage("user/dc", user);
Assert.IsNull(result.Body, "Invalid content");
Assert.AreEqual(new Uri(new Uri(uri), "/user/dc/3"), result.Headers.Location, "Invalid location");
Assert.AreEqual(HttpStatusCode.Created, result.StatusCode, "Invalid status code");
Assert.AreEqual("User id '3' created with 'Lisa Baia'", result.StatusDescription, "Invalid status description");
}
[Test]
public void XElementGetForObject()
{
template.MessageConverters.Add(new XElementHttpMessageConverter());
XElement result = template.GetForObject<XElement>("user/xml/{id}", "1");
Assert.IsNotNull(result, "Invalid content");
Assert.AreEqual("1", result.Element("ID").Value, "Invalid content");
Assert.AreEqual("Bruno Baïa", result.Element("Name").Value, "Invalid content");
}
[Test]
public void XElementPostForMessage()
{
template.MessageConverters.Add(new XElementHttpMessageConverter());
XElement user = new XElement("User",
new XElement("Name", "Lisa Baia"));
HttpResponseMessage result = template.PostForMessage("user/xml", user);
Assert.IsNull(result.Body, "Invalid content");
Assert.AreEqual(new Uri(new Uri(uri), "/user/xml/3"), result.Headers.Location, "Invalid location");
Assert.AreEqual(HttpStatusCode.Created, result.StatusCode, "Invalid status code");
Assert.AreEqual("User id '3' created with 'Lisa Baia'", result.StatusDescription, "Invalid status description");
}
#region REST test service
[DataContract]
public class User
{
[DataMember]
public string ID { get; set; }
[DataMember]
public string Name { get; set; }
}
[ServiceContract]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class TestService
{
private IList<User> users;
public TestService()
{
users = new List<User>();
users.Add(new User() { ID = "1", Name = "Bruno Baïa" });
users.Add(new User() { ID = "2", Name = "Marie Baia" });
}
[OperationContract]
[WebGet(UriTemplate = "user/dc/{id}")]
public User GetUserDataContract(string id)
{
WebOperationContext context = WebOperationContext.Current;
foreach (User user in this.users)
{
if (user.ID.Equals(id, StringComparison.InvariantCultureIgnoreCase))
{
return user;
}
}
context.OutgoingResponse.SetStatusAsNotFound(String.Format("User with id '{0}' not found", id));
return null;
}
[OperationContract]
[WebInvoke(UriTemplate = "user/dc", Method = "POST")]
public void CreateDataContract(User user)
{
WebOperationContext context = WebOperationContext.Current;
UriTemplateMatch match = context.IncomingRequest.UriTemplateMatch;
UriTemplate template = new UriTemplate("/user/dc/{id}");
MediaType mediaType = MediaType.Parse(context.IncomingRequest.ContentType);
if (!String.IsNullOrEmpty(user.ID))
{
context.OutgoingResponse.StatusCode = HttpStatusCode.BadRequest;
context.OutgoingResponse.StatusDescription = String.Format("User id '{0}' already exists", user.ID);
return;
}
user.ID = (users.Count + 1).ToString(); // generate new ID
users.Add(user);
Uri uri = template.BindByPosition(match.BaseUri, user.ID);
context.OutgoingResponse.SetStatusAsCreated(uri);
context.OutgoingResponse.StatusDescription = String.Format("User id '{0}' created with '{1}'", user.ID, user.Name);
}
[OperationContract]
[WebGet(UriTemplate = "user/xml/{id}")]
public XElement GetUserXElement(string id)
{
WebOperationContext context = WebOperationContext.Current;
foreach (User user in this.users)
{
if (user.ID.Equals(id, StringComparison.InvariantCultureIgnoreCase))
{
return new XElement("User",
new XElement("ID", user.ID),
new XElement("Name", user.Name));
}
}
context.OutgoingResponse.SetStatusAsNotFound(String.Format("User with id '{0}' not found", id));
return null;
}
[OperationContract]
[WebInvoke(UriTemplate = "user/xml", Method = "POST")]
public void CreateXElement(XElement user)
{
WebOperationContext context = WebOperationContext.Current;
UriTemplateMatch match = context.IncomingRequest.UriTemplateMatch;
UriTemplate template = new UriTemplate("/user/xml/{id}");
MediaType mediaType = MediaType.Parse(context.IncomingRequest.ContentType);
if (user.Element("ID") != null && !String.IsNullOrEmpty(user.Element("ID").Value))
{
context.OutgoingResponse.StatusCode = HttpStatusCode.BadRequest;
context.OutgoingResponse.StatusDescription = String.Format("User id '{0}' already exists", user.Element("ID"));
return;
}
User newUser = new User();
newUser.ID = (users.Count + 1).ToString(); // generate new ID
newUser.Name = user.Element("Name").Value;
users.Add(newUser);
Uri uri = template.BindByPosition(match.BaseUri, newUser.ID);
context.OutgoingResponse.SetStatusAsCreated(uri);
context.OutgoingResponse.StatusDescription = String.Format("User id '{0}' created with '{1}'", newUser.ID, newUser.Name);
}
}
#endregion
}
}
#endif

View File

@@ -1,123 +0,0 @@
#region License
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System.Text;
using NUnit.Framework;
namespace Spring.Http.Converters.Xml
{
/// <summary>
/// Unit tests for the XmlSerializableHttpMessageConverter class.
/// </summary>
/// <author>Bruno Baia</author>
[TestFixture]
public class XmlSerializableHttpMessageConverterTests
{
private XmlSerializableHttpMessageConverter converter;
[SetUp]
public void SetUp()
{
converter = new XmlSerializableHttpMessageConverter();
}
[Test]
public void CanRead()
{
Assert.IsTrue(converter.CanRead(typeof(CustomClass), new MediaType("application", "xml")));
Assert.IsTrue(converter.CanRead(typeof(CustomClass), new MediaType("text", "xml")));
Assert.IsTrue(converter.CanRead(typeof(CustomClass), new MediaType("application", "soap+xml"))); // application/*+xml
Assert.IsFalse(converter.CanRead(typeof(CustomClass), new MediaType("text", "plain")));
}
[Test]
public void CanWrite()
{
Assert.IsTrue(converter.CanWrite(typeof(CustomClass), new MediaType("application", "xml")));
Assert.IsTrue(converter.CanWrite(typeof(CustomClass), new MediaType("text", "xml")));
Assert.IsTrue(converter.CanWrite(typeof(CustomClass), new MediaType("application", "soap+xml"))); // application/*+xml
Assert.IsFalse(converter.CanWrite(typeof(CustomClass), new MediaType("text", "plain")));
}
[Test]
public void Read()
{
string body = @"<CustomClass xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'>
<ID>1</ID>
<Name>Bruno Baïa</Name>
</CustomClass>";
MockHttpInputMessage message = new MockHttpInputMessage(body, Encoding.UTF8);
CustomClass result = converter.Read<CustomClass>(message);
Assert.IsNotNull(result, "Invalid result");
Assert.AreEqual("1", result.ID, "Invalid result");
Assert.AreEqual("Bruno Baïa", result.Name, "Invalid result");
}
[Test]
public void Write()
{
string expectedBody = "<CustomClass xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><ID>1</ID><Name>Bruno Baïa</Name></CustomClass>";
CustomClass body = new CustomClass("1", "Bruno Baïa");
MockHttpOutputMessage message = new MockHttpOutputMessage();
converter.Write(body, null, message);
Assert.AreEqual(expectedBody, message.GetBodyAsString(Encoding.UTF8), "Invalid result");
Assert.AreEqual(new MediaType("application", "xml"), message.Headers.ContentType, "Invalid content-type");
//Assert.IsTrue(message.Headers.ContentLength > -1, "Invalid content-length");
}
#region Test classes
public class CustomClass
{
private string _id;
private string _name;
public string ID
{
get { return _id; }
set { _id = value; }
}
public string Name
{
get { return _name; }
set { _name = value; }
}
public CustomClass()
{
}
public CustomClass(string id, string name)
{
this._id = id;
this._name = name;
}
}
#endregion
}
}

View File

@@ -1,336 +0,0 @@
#region License
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System;
using NUnit.Framework;
namespace Spring.Http
{
/// <summary>
/// Unit tests for the HttpHeaders class.
/// </summary>
/// <author>Arjen Poutsma</author>
/// <author>Bruno Baia (.NET)</author>
[TestFixture]
public class HttpHeadersTests
{
private HttpHeaders headers;
[SetUp]
public void SetUp()
{
headers = new HttpHeaders();
}
[Test]
public void AcceptGet()
{
Assert.IsEmpty(headers.Accept);
headers.Add("Accept", "text/plain; q=0.5");
headers.Add("Accept", "text/html");
headers.Add("Accept", "text/x-dvi; q=0.8");
headers.Add("Accept", "text/x-c");
MediaType[] mediaTypes = headers.Accept;
Assert.NotNull(mediaTypes, "No media types returned");
Assert.AreEqual(4, mediaTypes.Length, "Invalid amount of media types");
Assert.AreEqual("text/plain;q=0.5", mediaTypes[0].ToString());
Assert.AreEqual("text/html", mediaTypes[1].ToString());
Assert.AreEqual("text/x-dvi;q=0.8", mediaTypes[2].ToString());
Assert.AreEqual("text/x-c", mediaTypes[3].ToString());
}
[Test]
public void AcceptSet()
{
MediaType mediaType1 = new MediaType("text", "html");
MediaType mediaType2 = new MediaType("text", "plain");
MediaType[] mediaTypes = new MediaType[2] { mediaType1, mediaType2 };
headers.Accept = mediaTypes;
Assert.AreEqual(mediaTypes, headers.Accept, "Invalid Accept header");
Assert.AreEqual("text/html,text/plain", headers["Accept"], "Invalid Accept header");
}
//[Test]
//public void acceptCharsets()
//{
// Charset charset1 = Charset.forName("UTF-8");
// Charset charset2 = Charset.forName("ISO-8859-1");
// List<Charset> charsets = new ArrayList<Charset>(2);
// charsets.add(charset1);
// charsets.add(charset2);
// headers.setAcceptCharset(charsets);
// Assert.AreEqual("Invalid Accept header", charsets, headers.getAcceptCharset());
// Assert.AreEqual("Invalid Accept header", "utf-8, iso-8859-1", headers.getFirst("Accept-Charset"));
//}
[Test]
public void AllowGet()
{
Assert.IsEmpty(headers.Allow);
headers.Add("Allow", "PUT");
headers.Add("Allow", "POST");
HttpMethod[] methods = headers.Allow;
Assert.NotNull(methods, "No methods returned");
Assert.AreEqual(2, methods.Length, "Invalid amount of HTTP methods");
Assert.AreEqual(HttpMethod.PUT, methods[0]);
Assert.AreEqual(HttpMethod.POST, methods[1]);
}
[Test]
public void AllowSet()
{
HttpMethod[] methods = new HttpMethod[2] { HttpMethod.GET, HttpMethod.POST };
headers.Allow = methods;
Assert.AreEqual(methods, headers.Allow, "Invalid Allow header");
Assert.AreEqual("GET,POST", headers["Allow"], "Invalid Allow header");
}
[Test]
public void ContentLength()
{
long length = 42;
headers.ContentLength = length;
Assert.AreEqual(length, headers.ContentLength, "Invalid Content-Length header");
Assert.AreEqual("42", headers["Content-Length"], "Invalid Content-Length header");
}
[Test]
public void ContentTypeGet()
{
Assert.IsNull(headers.ContentType);
headers.Set("Content-Type", "text/html;charset=UTF-8");
Assert.AreEqual("text/html;charset=UTF-8", headers.ContentType.ToString(), "Invalid Content-Type header");
}
[Test]
[ExpectedException(typeof(NotSupportedException))]
public void ContentTypeGetMultipleValues()
{
headers.Add("Content-Type", "text/html");
headers.Add("Content-Type", "application/xml");
MediaType mediaType = headers.ContentType;
}
[Test]
public void ContentTypeSet()
{
MediaType contentType = new MediaType("text", "html", "UTF-8");
headers.ContentType = contentType;
Assert.AreEqual(contentType, headers.ContentType, "Invalid Content-Type header");
Assert.AreEqual("text/html;charset=UTF-8", headers["Content-Type"], "Invalid Content-Type header");
}
[Test]
public void Location()
{
Uri location = new Uri("http://www.example.com/hotels");
headers.Location = location;
Assert.AreEqual(location, headers.Location, "Invalid Location header");
Assert.AreEqual("http://www.example.com/hotels", headers["Location"], "Invalid Location header");
}
[Test]
public void ETag()
{
string eTag = "v2.6";
headers.ETag = eTag;
Assert.AreEqual(eTag, headers.ETag, "Invalid ETag header");
Assert.AreEqual("\"v2.6\"", headers["ETag"], "Invalid ETag header");
}
[Test]
public void ETagWithWeaknessIndicator()
{
string eTag = "W/\"v2.6\"";
headers.ETag = eTag;
Assert.AreEqual(eTag, headers.ETag, "Invalid ETag header");
Assert.AreEqual(eTag, headers["ETag"], "Invalid ETag header");
}
[Test]
public void IfNoneMatchGet()
{
Assert.IsEmpty(headers.IfNoneMatch);
headers.Add("If-None-Match", "v1.0");
headers.Add("If-None-Match", "v2.0");
string[] eTags = headers.IfNoneMatch;
Assert.NotNull(eTags, "No eTags returned");
Assert.AreEqual(2, eTags.Length, "Invalid amount of eTags");
Assert.AreEqual("v1.0", eTags[0]);
Assert.AreEqual("v2.0", eTags[1]);
}
[Test]
public void IfNoneMatchSet()
{
string ifNoneMatch1 = "v2.6";
string ifNoneMatch2 = "v2.7";
string[] ifNoneMatchArray = new string[2] { ifNoneMatch1, ifNoneMatch2 };
headers.IfNoneMatch = ifNoneMatchArray;
Assert.AreEqual(ifNoneMatchArray, headers.IfNoneMatch, "Invalid If-None-Match header");
Assert.AreEqual("\"v2.6\",\"v2.7\"", headers.Get("If-None-Match"), "Invalid If-None-Match header");
}
[Test]
public void Date()
{
DateTime date = new DateTime(2008, 12, 18, 10, 20, 00, DateTimeKind.Utc);
headers.Date = date;
Assert.AreEqual(date, headers.Date, "Invalid Date header");
Assert.AreEqual("Thu, 18 Dec 2008 10:20:00 GMT", headers["date"], "Invalid Date header");
// RFC 850
headers.Set("Date", "Thursday, 18-Dec-08 10:20:00 GMT");
Assert.AreEqual(date, headers.Date, "Invalid Date header");
}
//[Test]//(expected = IllegalArgumentException.class)
//public void DateInvalid()
//{
// headers.Set("Date", "Foo Bar Baz");
// Assert.IsNotNull(headers.Date);
//}
//[Test]
//public void dateOtherLocale() {
// Locale defaultLocale = Locale.getDefault();
// try {
// Locale.setDefault(new Locale("nl", "nl"));
// Calendar calendar = new GregorianCalendar(2008, 11, 18, 11, 20);
// calendar.setTimeZone(TimeZone.getTimeZone("CET"));
// long date = calendar.getTimeInMillis();
// headers.setDate(date);
// Assert.AreEqual("Invalid Date header", "Thu, 18 Dec 2008 10:20:00 GMT", headers.getFirst("date"));
// Assert.AreEqual("Invalid Date header", date, headers.getDate());
// }
// finally {
// Locale.setDefault(defaultLocale);
// }
//}
[Test]
public void LastModified()
{
DateTime date = new DateTime(2008, 12, 18, 10, 20, 00, DateTimeKind.Utc);
headers.LastModified = date;
Assert.AreEqual(date, headers.LastModified, "Invalid Last-Modified header");
Assert.AreEqual("Thu, 18 Dec 2008 10:20:00 GMT", headers["Last-Modified"], "Invalid Last-Modified header");
}
[Test]
public void Expires()
{
string date = "Thu, 18 Dec 2008 10:20:00 GMT";
headers.Expires = date;
Assert.AreEqual(date, headers.Expires, "Invalid Expires header");
Assert.AreEqual("Thu, 18 Dec 2008 10:20:00 GMT", headers["Expires"], "Invalid Expires header");
}
[Test]
public void IfModifiedSince()
{
DateTime date = new DateTime(2008, 12, 18, 10, 20, 00, DateTimeKind.Utc);
headers.IfModifiedSince = date;
Assert.AreEqual(date, headers.IfModifiedSince, "Invalid If-Modified-Since header");
Assert.AreEqual("Thu, 18 Dec 2008 10:20:00 GMT", headers["If-Modified-Since"], "Invalid If-Modified-Since header");
}
[Test]
public void Pragma()
{
string pragma = "no-cache";
headers.Pragma = pragma;
Assert.AreEqual(pragma, headers.Pragma, "Invalid Pragma header");
Assert.AreEqual("no-cache", headers["pragma"], "Invalid Pragma header");
}
[Test]
public void CacheControl()
{
string cacheControl = "no-cache";
headers.CacheControl = cacheControl;
Assert.AreEqual(cacheControl, headers.CacheControl, "Invalid Cache-Control header");
Assert.AreEqual("no-cache", headers["cache-control"], "Invalid Cache-Control header");
}
//[Test]
//public void contentDisposition() {
// headers.setContentDispositionFormData("name", null);
// Assert.AreEqual("Invalid Content-Disposition header", "form-data; name=\"name\"", headers.getFirst("Content-Disposition"));
// headers.setContentDispositionFormData("name", "filename");
// Assert.AreEqual("Invalid Content-Disposition header", "form-data; name=\"name\"; filename=\"filename\"", headers.getFirst("Content-Disposition"));
//}
[Test]
public void GetSingleValue()
{
headers.Add("HeaderName", "1,2,3");
Assert.AreEqual("1,2,3", headers.GetSingleValue("HeaderName"));
}
[Test]
[ExpectedException(typeof(NotSupportedException))]
public void GetSingleValueWithMultipleValues()
{
headers.Add("HeaderName", "1");
headers.Add("HeaderName", "2");
headers.Add("HeaderName", "3");
headers.GetSingleValue("HeaderName");
}
[Test]
public void GetMultiValues()
{
headers.Add("HeaderName", "1,2,3");
Assert.AreEqual(3, headers.GetMultiValues("HeaderName").Length);
headers.Add("HeaderName", "4");
Assert.AreEqual(4, headers.GetMultiValues("HeaderName").Length);
}
}
}

View File

@@ -1,531 +0,0 @@
#region License
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System;
using System.Collections.Generic;
using NUnit.Framework;
namespace Spring.Http
{
/// <summary>
/// Unit tests for the MediaType class.
/// </summary>
/// <author>Arjen Poutsma</author>
/// <author>Juergen Hoeller</author>
/// <author>Bruno Baia (.NET)</author>
[TestFixture]
public class MediaTypeTests
{
[Test]
public void Includes()
{
MediaType textPlain = MediaType.TEXT_PLAIN;
Assert.IsTrue(textPlain.Includes(textPlain), "Equal types is not inclusive");
MediaType allText = new MediaType("text");
Assert.IsTrue(allText.Includes(textPlain), "All subtypes is not inclusive");
Assert.IsFalse(textPlain.Includes(allText), "All subtypes is inclusive");
Assert.IsTrue(MediaType.ALL.Includes(textPlain), "All types is not inclusive");
Assert.IsFalse(textPlain.Includes(MediaType.ALL), "All types is inclusive");
Assert.IsTrue(MediaType.ALL.Includes(textPlain), "All types is not inclusive");
Assert.IsFalse(textPlain.Includes(MediaType.ALL), "All types is inclusive");
MediaType applicationSoapXml = new MediaType("application", "soap+xml");
MediaType applicationWildcardXml = new MediaType("application", "*+xml");
Assert.IsTrue(applicationSoapXml.Includes(applicationSoapXml));
Assert.IsTrue(applicationWildcardXml.Includes(applicationWildcardXml));
Assert.IsTrue(applicationWildcardXml.Includes(applicationSoapXml));
Assert.IsFalse(applicationSoapXml.Includes(applicationWildcardXml));
}
[Test]
public void IsCompatible()
{
MediaType textPlain = MediaType.TEXT_PLAIN;
Assert.IsTrue(textPlain.IsCompatibleWith(textPlain), "Equal types is not compatible");
MediaType allText = new MediaType("text");
Assert.IsTrue(allText.IsCompatibleWith(textPlain), "All subtypes is not compatible");
Assert.IsTrue(textPlain.IsCompatibleWith(allText), "All subtypes is not compatible");
Assert.IsTrue(MediaType.ALL.IsCompatibleWith(textPlain), "All types is not compatible");
Assert.IsTrue(textPlain.IsCompatibleWith(MediaType.ALL), "All types is not compatible");
Assert.IsTrue(MediaType.ALL.IsCompatibleWith(textPlain), "All types is not compatible");
Assert.IsTrue(textPlain.IsCompatibleWith(MediaType.ALL), "All types is compatible");
MediaType applicationSoapXml = new MediaType("application", "soap+xml");
MediaType applicationWildcardXml = new MediaType("application", "*+xml");
Assert.IsTrue(applicationSoapXml.IsCompatibleWith(applicationSoapXml));
Assert.IsTrue(applicationWildcardXml.IsCompatibleWith(applicationWildcardXml));
Assert.IsTrue(applicationWildcardXml.IsCompatibleWith(applicationSoapXml));
Assert.IsTrue(applicationSoapXml.IsCompatibleWith(applicationWildcardXml));
}
[Test]
public void TestToString()
{
MediaType mediaType = new MediaType("text", "plain", 0.7);
String result = mediaType.ToString();
Assert.AreEqual("text/plain;q=0.7", result, "Invalid toString() returned");
}
//[Test](expected= IllegalArgumentException.class)
//public void slashInType() {
// new MediaType("text/plain");
//}
//[Test](expected= IllegalArgumentException.class)
//public void slashInSubtype() {
// new MediaType("text", "/");
//}
[Test]
public void GetDefaultQualityValue()
{
MediaType mediaType = new MediaType("text", "plain");
Assert.AreEqual(1, mediaType.QualityValue, "Invalid quality value");
}
[Test]
public void Parse()
{
string s = "audio/*; q=0.2";
MediaType mediaType = MediaType.Parse(s);
Assert.AreEqual("audio", mediaType.Type, "Invalid type");
Assert.AreEqual("*", mediaType.Subtype, "Invalid subtype");
Assert.AreEqual(0.2, mediaType.QualityValue, "Invalid quality factor");
}
[Test]
[ExpectedException(typeof(ArgumentException))]
public void ParseNoSubtype()
{
MediaType.Parse("audio");
}
[Test]
[ExpectedException(typeof(ArgumentException))]
public void ParseNoSubtypeSlash()
{
MediaType.Parse("audio/");
}
//[Test](expected = IllegalArgumentException.class)
//public void parseIllegalType() {
// MediaType.parse("audio(/basic");
//}
//[Test](expected = IllegalArgumentException.class)
//public void parseIllegalSubtype() {
// MediaType.parse("audio/basic)");
//}
//[Test](expected = IllegalArgumentException.class)
//public void parseEmptyParameterAttribute() {
// MediaType.parse("audio/*;=value");
//}
//[Test](expected = IllegalArgumentException.class)
//public void parseMediaTypeEmptyParameterValue() {
// MediaType.parseMediaType("audio/*;attr=");
//}
//[Test](expected = IllegalArgumentException.class)
//public void parseIllegalParameterAttribute() {
// MediaType.parse("audio/*;attr<=value");
//}
//[Test](expected = IllegalArgumentException.class)
//public void parseIllegalParameterValue() {
// MediaType.parse("audio/*;attr=v>alue");
//}
//[Test](expected = IllegalArgumentException.class)
//public void parseIllegalQualityFactor() {
// MediaType.parse("audio/basic;q=1.1");
//}
//[Test](expected = IllegalArgumentException.class)
//public void parseIllegalCharset() {
// MediaType.parse("text/html; charset=foo-bar");
//}
//[Test]
//public void parseQuotedParameterValue() {
// MediaType.parse("audio/*;attr=\"v>alue\"");
//}
//[Test](expected = IllegalArgumentException.class)
//public void parseIllegalQuotedParameterValue() {
// MediaType.parse("audio/*;attr=\"");
//}
//[Test]
//public void parseCharset() throws Exception {
// String s = "text/html; charset=iso-8859-1";
// MediaType mediaType = MediaType.parse(s);
// Assert.AreEqual("Invalid type", "text", mediaType.getType());
// Assert.AreEqual("Invalid subtype", "html", mediaType.getSubtype());
// Assert.AreEqual("Invalid charset", Charset.forName("ISO-8859-1"), mediaType.getCharSet());
//}
//[Test]
//public void parseQuotedCharset() {
// String s = "application/xml;charset=\"utf-8\"";
// MediaType mediaType = MediaType.parse(s);
// Assert.AreEqual("Invalid type", "application", mediaType.getType());
// Assert.AreEqual("Invalid subtype", "xml", mediaType.getSubtype());
// Assert.AreEqual("Invalid charset", Charset.forName("UTF-8"), mediaType.getCharSet());
//}
[Test]
public void ParseURLConnectionMediaType()
{
string s = "*; q=.2";
MediaType mediaType = MediaType.Parse(s);
Assert.AreEqual(mediaType.Type, "*", "Invalid type");
Assert.AreEqual("*", mediaType.Subtype, "Invalid subtype");
Assert.AreEqual(0.2, mediaType.QualityValue, "Invalid quality factor");
}
[Test]
public void CompareTo()
{
MediaType audioBasic = new MediaType("audio", "basic");
MediaType audio = new MediaType("audio");
MediaType audioWave = new MediaType("audio", "wave");
MediaType audioBasicLevel = new MediaType("audio", "basic", SingletonDictionary<string, string>("level", "1"));
MediaType audioBasic07 = new MediaType("audio", "basic", 0.7);
// equal
Assert.AreEqual(0, audioBasic.CompareTo(audioBasic), "Invalid comparison result");
Assert.AreEqual(0, audio.CompareTo(audio), "Invalid comparison result");
Assert.AreEqual(0, audioBasicLevel.CompareTo(audioBasicLevel), "Invalid comparison result");
Assert.IsTrue(audioBasicLevel.CompareTo(audio) > 0, "Invalid comparison result");
List<MediaType> expected = new List<MediaType>();
expected.Add(audio);
expected.Add(audioBasic);
expected.Add(audioBasicLevel);
expected.Add(audioBasic07);
expected.Add(audioWave);
List<MediaType> result = new List<MediaType>(expected);
// shuffle & sort 10 times
for (int i = 0; i < 10; i++)
{
result.Sort(ShuffleComparison);
result.Sort();
for (int j = 0; j < result.Count; j++)
{
Assert.AreSame(expected[j], result[j], "Invalid media type at " + j + ", run " + i);
}
}
}
[Test]
public void CompareToConsistentWithEquals()
{
MediaType m1 = MediaType.Parse("text/html; q=0.7; charset=iso-8859-1");
MediaType m2 = MediaType.Parse("text/html; charset=iso-8859-1; q=0.7");
Assert.AreEqual(m1, m2, "Media types not equal");
Assert.AreEqual(0, m1.CompareTo(m2), "compareTo() not consistent with equals");
Assert.AreEqual(0, m2.CompareTo(m1), "compareTo() not consistent with equals");
m1 = MediaType.Parse("text/html; q=0.7; charset=iso-8859-1");
m2 = MediaType.Parse("text/html; Q=0.7; charset=iso-8859-1");
Assert.AreEqual(m1, m2, "Media types not equal");
Assert.AreEqual(0, m1.CompareTo(m2), "compareTo() not consistent with equals");
Assert.AreEqual(0, m2.CompareTo(m1), "compareTo() not consistent with equals");
}
[Test]
public void CompareToCaseSensitivity()
{
MediaType m1 = new MediaType("audio", "basic");
MediaType m2 = new MediaType("Audio", "Basic");
Assert.AreEqual(0, m1.CompareTo(m2), "Invalid comparison result");
Assert.AreEqual(0, m2.CompareTo(m1), "Invalid comparison result");
m1 = new MediaType("audio", "basic", SingletonDictionary<string, string>("foo", "bar"));
m2 = new MediaType("audio", "basic", SingletonDictionary<string, string>("Foo", "bar"));
Assert.AreEqual(0, m1.CompareTo(m2), "Invalid comparison result");
Assert.AreEqual(0, m2.CompareTo(m1), "Invalid comparison result");
m1 = new MediaType("audio", "basic", SingletonDictionary<string, string>("foo", "bar"));
m2 = new MediaType("audio", "basic", SingletonDictionary<string, string>("foo", "Bar"));
Assert.IsTrue(m1.CompareTo(m2) != 0, "Invalid comparison result");
Assert.IsTrue(m2.CompareTo(m1) != 0, "Invalid comparison result");
}
[Test]
public void SpecificityComparator()
{
MediaType audioBasic = new MediaType("audio", "basic");
MediaType audioWave = new MediaType("audio", "wave");
MediaType audio = new MediaType("audio");
MediaType audio03 = new MediaType("audio", "*", 0.3);
MediaType audio07 = new MediaType("audio", "*", 0.7);
MediaType audioBasicLevel = new MediaType("audio", "basic", SingletonDictionary<string, string>("level", "1"));
MediaType textHtml = new MediaType("text", "html");
MediaType all = MediaType.ALL;
IComparer<MediaType> comp = MediaType.SPECIFICITY_COMPARER;
// equal
Assert.AreEqual(0, comp.Compare(audioBasic,audioBasic), "Invalid comparison result");
Assert.AreEqual(0, comp.Compare(audio, audio), "Invalid comparison result");
Assert.AreEqual(0, comp.Compare(audio07, audio07), "Invalid comparison result");
Assert.AreEqual(0, comp.Compare(audio03, audio03), "Invalid comparison result");
Assert.AreEqual(0, comp.Compare(audioBasicLevel, audioBasicLevel), "Invalid comparison result");
// specific to unspecific
Assert.IsTrue(comp.Compare(audioBasic, audio) < 0, "Invalid comparison result");
Assert.IsTrue(comp.Compare(audioBasic, all) < 0, "Invalid comparison result");
Assert.IsTrue(comp.Compare(audio, all) < 0, "Invalid comparison result");
// unspecific to specific
Assert.IsTrue(comp.Compare(audio, audioBasic) > 0, "Invalid comparison result");
Assert.IsTrue(comp.Compare(all, audioBasic) > 0, "Invalid comparison result");
Assert.IsTrue(comp.Compare(all, audio) > 0, "Invalid comparison result");
// qualifiers
Assert.IsTrue(comp.Compare(audio, audio07) < 0, "Invalid comparison result");
Assert.IsTrue(comp.Compare(audio07, audio) > 0, "Invalid comparison result");
Assert.IsTrue(comp.Compare(audio07, audio03) < 0, "Invalid comparison result");
Assert.IsTrue(comp.Compare(audio03, audio07) > 0, "Invalid comparison result");
Assert.IsTrue(comp.Compare(audio03, all) < 0, "Invalid comparison result");
Assert.IsTrue(comp.Compare(all, audio03) > 0, "Invalid comparison result");
// other parameters
Assert.IsTrue(comp.Compare(audioBasic, audioBasicLevel) > 0, "Invalid comparison result");
Assert.IsTrue(comp.Compare(audioBasicLevel, audioBasic) < 0, "Invalid comparison result");
// different types
Assert.AreEqual(0, comp.Compare(audioBasic, textHtml), "Invalid comparison result");
Assert.AreEqual(0, comp.Compare(textHtml, audioBasic), "Invalid comparison result");
// different subtypes
Assert.AreEqual(0, comp.Compare(audioBasic, audioWave), "Invalid comparison result");
Assert.AreEqual(0, comp.Compare(audioWave, audioBasic), "Invalid comparison result");
}
[Test]
public void SortBySpecificityRelated()
{
MediaType audioBasic = new MediaType("audio", "basic");
MediaType audio = new MediaType("audio");
MediaType audio03 = new MediaType("audio", "*", 0.3);
MediaType audio07 = new MediaType("audio", "*", 0.7);
MediaType audioBasicLevel = new MediaType("audio", "basic", SingletonDictionary<string, string>("level", "1"));
MediaType all = MediaType.ALL;
List<MediaType> expected = new List<MediaType>();
expected.Add(audioBasicLevel);
expected.Add(audioBasic);
expected.Add(audio);
expected.Add(audio07);
expected.Add(audio03);
expected.Add(all);
List<MediaType> result = new List<MediaType>(expected);
// shuffle & sort 10 times
for (int i = 0; i < 10; i++)
{
result.Sort(ShuffleComparison);
MediaType.SortBySpecificity(result);
for (int j = 0; j < result.Count; j++)
{
Assert.AreSame(expected[j], result[j], "Invalid media type at " + j);
}
}
}
[Test]
[Ignore]
public void SortBySpecificityUnrelated()
{
MediaType audioBasic = new MediaType("audio", "basic");
MediaType audioWave = new MediaType("audio", "wave");
MediaType textHtml = new MediaType("text", "html");
List<MediaType> expected = new List<MediaType>();
expected.Add(textHtml);
expected.Add(audioBasic);
expected.Add(audioWave);
List<MediaType> result = new List<MediaType>(expected);
MediaType.SortBySpecificity(result);
for (int i = 0; i < result.Count; i++)
{
Assert.AreSame(expected[i], result[i], "Invalid media type at " + i);
}
}
[Test]
public void QualityComparator()
{
MediaType audioBasic = new MediaType("audio", "basic");
MediaType audioWave = new MediaType("audio", "wave");
MediaType audio = new MediaType("audio");
MediaType audio03 = new MediaType("audio", "*", 0.3);
MediaType audio07 = new MediaType("audio", "*", 0.7);
MediaType audioBasicLevel = new MediaType("audio", "basic", SingletonDictionary<string, string>("level", "1"));
MediaType textHtml = new MediaType("text", "html");
MediaType all = MediaType.ALL;
IComparer<MediaType> comp = MediaType.QUALITY_VALUE_COMPARER;
// equal
Assert.AreEqual(0, comp.Compare(audioBasic, audioBasic), "Invalid comparison result");
Assert.AreEqual(0, comp.Compare(audio, audio), "Invalid comparison result");
Assert.AreEqual(0, comp.Compare(audio07, audio07), "Invalid comparison result");
Assert.AreEqual(0, comp.Compare(audio03, audio03), "Invalid comparison result");
Assert.AreEqual(0, comp.Compare(audioBasicLevel, audioBasicLevel), "Invalid comparison result");
// specific to unspecific
Assert.IsTrue(comp.Compare(audioBasic, audio) < 0, "Invalid comparison result");
Assert.IsTrue(comp.Compare(audioBasic, all) < 0, "Invalid comparison result");
Assert.IsTrue(comp.Compare(audio, all) < 0, "Invalid comparison result");
// unspecific to specific
Assert.IsTrue(comp.Compare(audio, audioBasic) > 0, "Invalid comparison result");
Assert.IsTrue(comp.Compare(all, audioBasic) > 0, "Invalid comparison result");
Assert.IsTrue(comp.Compare(all, audio) > 0, "Invalid comparison result");
// qualifiers
Assert.IsTrue(comp.Compare(audio, audio07) < 0, "Invalid comparison result");
Assert.IsTrue(comp.Compare(audio07, audio) > 0, "Invalid comparison result");
Assert.IsTrue(comp.Compare(audio07, audio03) < 0, "Invalid comparison result");
Assert.IsTrue(comp.Compare(audio03, audio07) > 0, "Invalid comparison result");
Assert.IsTrue(comp.Compare(audio03, all) > 0, "Invalid comparison result");
Assert.IsTrue(comp.Compare(all, audio03) < 0, "Invalid comparison result");
// other parameters
Assert.IsTrue(comp.Compare(audioBasic, audioBasicLevel) > 0, "Invalid comparison result");
Assert.IsTrue(comp.Compare(audioBasicLevel, audioBasic) < 0, "Invalid comparison result");
// different types
Assert.AreEqual(0, comp.Compare(audioBasic, textHtml), "Invalid comparison result");
Assert.AreEqual(0, comp.Compare(textHtml, audioBasic), "Invalid comparison result");
// different subtypes
Assert.AreEqual(0, comp.Compare(audioBasic, audioWave), "Invalid comparison result");
Assert.AreEqual(0, comp.Compare(audioWave, audioBasic), "Invalid comparison result");
}
[Test]
public void SortByQualityRelated()
{
MediaType audioBasic = new MediaType("audio", "basic");
MediaType audio = new MediaType("audio");
MediaType audio03 = new MediaType("audio", "*", 0.3);
MediaType audio07 = new MediaType("audio", "*", 0.7);
MediaType audioBasicLevel = new MediaType("audio", "basic", SingletonDictionary<string, string>("level", "1"));
MediaType all = MediaType.ALL;
List<MediaType> expected = new List<MediaType>();
expected.Add(audioBasicLevel);
expected.Add(audioBasic);
expected.Add(audio);
expected.Add(all);
expected.Add(audio07);
expected.Add(audio03);
List<MediaType> result = new List<MediaType>(expected);
// shuffle & sort 10 times
for (int i = 0; i < 10; i++)
{
result.Sort(ShuffleComparison);
MediaType.SortByQualityValue(result);
for (int j = 0; j < result.Count; j++)
{
Assert.AreSame(expected[j], result[j], "Invalid media type at " + j);
}
}
}
[Test]
[Ignore]
public void SortByQualityUnrelated()
{
MediaType audioBasic = new MediaType("audio", "basic");
MediaType audioWave = new MediaType("audio", "wave");
MediaType textHtml = new MediaType("text", "html");
List<MediaType> expected = new List<MediaType>();
expected.Add(textHtml);
expected.Add(audioBasic);
expected.Add(audioWave);
List<MediaType> result = new List<MediaType>(expected);
MediaType.SortBySpecificity(result);
for (int i = 0; i < result.Count; i++)
{
Assert.AreSame(expected[i], result[i], "Invalid media type at " + i);
}
}
//[Test]
//public void testWithConversionService() {
// ConversionService conversionService = ConversionServiceFactory.createDefaultConversionService();
// Assert.IsTrue(conversionService.canConvert(String.class, MediaType.class));
// MediaType mediaType = MediaType.parseMediaType("application/xml");
// Assert.AreEqual(mediaType, conversionService.convert("application/xml", MediaType.class));
//}
#region Utils
private static int ShuffleComparison(MediaType mediaType1, MediaType mediaType2)
{
if (mediaType1 == mediaType2)
{
return 0;
}
Random rd = new Random();
return rd.Next(-1, 2);
}
private static IDictionary<TKey, TValue> SingletonDictionary<TKey, TValue>(TKey key, TValue value)
{
IDictionary<TKey, TValue> dictionary = new Dictionary<TKey, TValue>(1);
dictionary.Add(key, value);
return dictionary;
}
#endregion
}
}

View File

@@ -1,58 +0,0 @@
#region License
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System;
using System.IO;
using System.Text;
namespace Spring.Http
{
/// <summary>
/// Mocked IHttpInputMessage implementation.
/// </summary>
/// <author>Arjen Poutsma</author>
/// <author>Bruno Baia (.NET)</author>
public class MockHttpInputMessage : IHttpInputMessage
{
private HttpHeaders headers;
private Stream body;
public MockHttpInputMessage(byte[] body)
{
this.headers = new HttpHeaders();
this.body = new MemoryStream(body);
}
public MockHttpInputMessage(string body, Encoding charset)
: this(charset.GetBytes(body))
{
}
public HttpHeaders Headers
{
get { return this.headers; }
}
public Stream Body
{
get { return this.body; }
}
}
}

View File

@@ -1,72 +0,0 @@
#region License
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System;
using System.IO;
using System.Text;
namespace Spring.Http
{
/// <summary>
/// Mocked IHttpOutputMessage implementation.
/// </summary>
/// <author>Arjen Poutsma</author>
/// <author>Bruno Baia (.NET)</author>
public class MockHttpOutputMessage : IHttpOutputMessage
{
private HttpHeaders headers;
private Action<Stream> body;
private byte[] bodyAsBytes;
public MockHttpOutputMessage()
{
this.headers = new HttpHeaders();
}
public HttpHeaders Headers
{
get { return this.headers; }
}
public Action<Stream> Body
{
set { this.body = value; }
}
public byte[] GetBodyAsBytes()
{
if (bodyAsBytes == null)
{
using (MemoryStream requestStream = new MemoryStream())
{
this.body(requestStream);
bodyAsBytes = requestStream.ToArray();
}
}
return bodyAsBytes;
}
public String GetBodyAsString(Encoding charset)
{
byte[] bytes = GetBodyAsBytes();
return charset.GetString(bytes);
}
}
}

View File

@@ -1,48 +0,0 @@
#region License
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System.Net;
using Spring.Util;
using NUnit.Framework;
namespace Spring.Http.Rest
{
/// <summary>
/// Unit tests for the HttpStatusCodeException class.
/// </summary>
/// <author>Bruno Baia</author>
[TestFixture]
public class HttpStatusCodeExceptionTests
{
[Test]
public void BinarySerialization()
{
HttpStatusCodeException exBefore = new HttpStatusCodeException(HttpStatusCode.Accepted, "Accepted description");
HttpStatusCodeException exAfter = SerializationTestUtils.BinarySerializeAndDeserialize(exBefore) as HttpStatusCodeException;
Assert.IsNotNull(exAfter);
Assert.AreEqual(HttpStatusCode.Accepted, exAfter.StatusCode, "Invalid status code");
Assert.AreEqual("Accepted description", exAfter.StatusDescription, "Invalid status description");
}
}
}

View File

@@ -1,660 +0,0 @@
#if NET_3_5
#region License
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System;
using System.Net;
using System.IO;
using System.Text;
using System.Threading;
using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.ServiceModel.Channels;
using NUnit.Framework;
namespace Spring.Http.Rest
{
/// <summary>
/// Integration tests for the RestTemplate class.
/// </summary>
/// <author>Arjen Poutsma</author>
/// <author>Bruno Baia (.NET)</author>
[TestFixture]
public class RestTemplateIntegrationTests
{
#region Logging
private static readonly Common.Logging.ILog LOG = Common.Logging.LogManager.GetLogger(typeof(RestTemplateIntegrationTests));
#endregion
private WebServiceHost webServiceHost;
private string uri = "http://localhost:1337";
private RestTemplate template;
private MediaType contentType;
[SetUp]
public void SetUp()
{
template = new RestTemplate(uri);
contentType = new MediaType("text", "plain");
webServiceHost = new WebServiceHost(typeof(TestService), new Uri(uri));
webServiceHost.Open();
}
[TearDown]
public void TearDown()
{
webServiceHost.Close();
}
#region Sync
[Test]
public void GetString()
{
string result = template.GetForObject<string>("users");
Assert.AreEqual("2", result, "Invalid content");
}
[Test]
public void GetStringVarArgsTemplateVariables()
{
string result = template.GetForObject<string>("user/{id}", 1);
Assert.AreEqual("Bruno Baïa", result, "Invalid content");
}
[Test]
public void GetStringDictionaryTemplateVariables()
{
IDictionary<string, object> uriVariables = new Dictionary<string, object>(1);
uriVariables.Add("id", 2);
string result = template.GetForObject<string>("user/{id}", uriVariables);
Assert.AreEqual("Marie Baia", result, "Invalid content");
}
[Test]
[ExpectedException(typeof(HttpClientErrorException),
ExpectedMessage = "The server returned 'User with id '5' not found' with the status code 404 - NotFound.")]
public void GetStringError()
{
string result = template.GetForObject<string>("user/{id}", 5);
}
[Test]
public void GetStringForMessage()
{
HttpResponseMessage<string> result = template.GetForMessage<string>("user/{id}", 1);
Assert.AreEqual("Bruno Baïa", result.Body, "Invalid content");
Assert.AreEqual(new MediaType("text", "plain", "utf-8"), result.Headers.ContentType, "Invalid content-type");
Assert.AreEqual(HttpStatusCode.OK, result.StatusCode, "Invalid status code");
Assert.AreEqual("OK", result.StatusDescription, "Invalid status description");
}
[Test]
[ExpectedException(typeof(RestClientException),
ExpectedMessage = "Could not extract response: no Content-Type found")]
public void GetStringNoResponse()
{
string result = template.GetForObject<string>("/nothing");
}
[Test]
public void HeadForHeaders()
{
HttpHeaders result = template.HeadForHeaders("head");
Assert.AreEqual("MyValue", result["MyHeader"], "Invalid header");
}
[Test]
public void PostStringForLocation()
{
Uri result = template.PostForLocation("user", "Lisa Baia");
Assert.AreEqual(new Uri(new Uri(uri), "/user/3"), result, "Invalid location");
}
[Test]
public void PostStringForMessage()
{
HttpResponseMessage<string> result = template.PostForMessage<string>("user", "Lisa Baia");
Assert.AreEqual(new Uri(new Uri(uri), "/user/3"), result.Headers.Location, "Invalid location");
Assert.AreEqual(HttpStatusCode.Created, result.StatusCode, "Invalid status code");
Assert.AreEqual("User id '3' created with 'Lisa Baia'", result.StatusDescription, "Invalid status description");
Assert.AreEqual("3", result.Body, "Invalid content");
}
[Test]
public void PostStringForObject()
{
string result = template.PostForObject<string>("user", "Lisa Baia");
Assert.AreEqual("3", result, "Invalid content");
}
[Test]
[ExpectedException(typeof(HttpClientErrorException),
ExpectedMessage = "The server returned 'Content cannot be null or empty' with the status code 400 - BadRequest.")]
public void PostStringForObjectWithError()
{
string result = template.PostForObject<string>("user", "");
}
[Test]
[ExpectedException(typeof(HttpClientErrorException),
ExpectedMessage = "The server returned 'Content cannot be null or empty' with the status code 400 - BadRequest.")]
public void PostStringNull()
{
template.PostForObject<string>("user", null);
}
[Test]
public void Put()
{
string result = template.GetForObject<string>("user/1");
Assert.AreEqual("Bruno Baïa", result, "Invalid content");
template.Put("user/1", "Bruno Baia");
result = template.GetForObject<string>("user/1");
Assert.AreEqual("Bruno Baia", result, "Invalid content");
}
[Test]
[ExpectedException(typeof(HttpClientErrorException),
ExpectedMessage = "The server returned 'User id '4' does not exist' with the status code 400 - BadRequest.")]
public void PutWithError()
{
template.Put("user/4", "Dinora Baia");
}
[Test]
public void Delete()
{
string result = template.GetForObject<string>("users");
Assert.AreEqual("2", result, "Invalid content");
template.Delete("user/2");
result = template.GetForObject<string>("users");
Assert.AreEqual("1", result, "Invalid content");
}
[Test]
[ExpectedException(typeof(HttpClientErrorException),
ExpectedMessage = "The server returned 'User id '10' does not exist' with the status code 400 - BadRequest.")]
public void DeleteWithError()
{
template.Delete("user/10");
}
[Test]
public void OptionsForAllow()
{
IList<HttpMethod> result = template.OptionsForAllow("allow");
Assert.AreEqual(3, result.Count, "Invalid response");
Assert.IsTrue(result.Contains(HttpMethod.GET), "Invalid response");
Assert.IsTrue(result.Contains(HttpMethod.HEAD), "Invalid response");
Assert.IsTrue(result.Contains(HttpMethod.PUT), "Invalid response");
}
[Test]
public void ExchangeForResponse()
{
HttpResponseMessage<string> result = template.Exchange<string>(
"user", HttpMethod.POST, new HttpEntity("Maryse Baia"));
Assert.AreEqual("3", result.Body, "Invalid content");
Assert.AreEqual(HttpStatusCode.Created, result.StatusCode, "Invalid status code");
Assert.AreEqual("User id '3' created with 'Maryse Baia'", result.StatusDescription, "Invalid status description");
}
[Test]
public void ExchangeForMessage()
{
HttpResponseMessage result = template.Exchange(
"user/1", HttpMethod.PUT, new HttpEntity("Bruno Baia"));
Assert.AreEqual(HttpStatusCode.OK, result.StatusCode, "Invalid status code");
Assert.AreEqual("User id '1' updated with 'Bruno Baia'", result.StatusDescription, "Invalid status description");
}
[Test]
public void ExchangeWithHeaders()
{
HttpHeaders headers = new HttpHeaders();
headers.ContentLength = 11;
HttpEntity entity = new HttpEntity("Maryse Baia", headers);
HttpResponseMessage<string> result = template.Exchange<string>(
"user", HttpMethod.POST, entity);
Assert.AreEqual("3", result.Body, "Invalid content");
Assert.AreEqual(HttpStatusCode.Created, result.StatusCode, "Invalid status code");
Assert.AreEqual("User id '3' created with 'Maryse Baia'", result.StatusDescription, "Invalid status description");
}
[Test]
[ExpectedException(typeof(HttpClientErrorException),
ExpectedMessage = "The server returned 'Not Found' with the status code 404 - NotFound.")]
public void ClientError()
{
template.Execute<object>("clienterror", HttpMethod.GET, null, null);
}
[Test]
[ExpectedException(typeof(HttpServerErrorException),
ExpectedMessage = "The server returned 'Internal Server Error' with the status code 500 - InternalServerError.")]
public void ServerError()
{
template.Execute<object>("servererror", HttpMethod.GET, null, null);
}
#endregion
#region Async
[Test]
public void GetStringAsync()
{
ManualResetEvent manualEvent = new ManualResetEvent(false);
Exception exception = null;
template.GetForObjectAsync<string>("users",
delegate(MethodCompletedEventArgs<string> args)
{
try
{
Assert.IsNull(args.Error, "Invalid response");
Assert.IsFalse(args.Cancelled, "Invalid response");
Assert.AreEqual("2", args.Response, "Invalid content");
}
catch (Exception ex)
{
exception = ex;
}
finally
{
manualEvent.Set();
}
});
manualEvent.WaitOne();
if (exception != null)
{
throw exception;
}
}
[Test]
public void GetStringForMessageAsync()
{
ManualResetEvent manualEvent = new ManualResetEvent(false);
Exception exception = null;
template.GetForMessageAsync<string>("user/{id}",
delegate(MethodCompletedEventArgs<HttpResponseMessage<string>> args)
{
try
{
Assert.IsNull(args.Error, "Invalid response");
Assert.IsFalse(args.Cancelled, "Invalid response");
Assert.AreEqual("Bruno Baïa", args.Response.Body, "Invalid content");
Assert.AreEqual(new MediaType("text", "plain", "utf-8"), args.Response.Headers.ContentType, "Invalid content-type");
Assert.AreEqual(HttpStatusCode.OK, args.Response.StatusCode, "Invalid status code");
Assert.AreEqual("OK", args.Response.StatusDescription, "Invalid status description");
}
catch (Exception ex)
{
exception = ex;
}
finally
{
manualEvent.Set();
}
}, 1);
manualEvent.WaitOne();
if (exception != null)
{
throw exception;
}
}
[Test]
public void PostStringForMessageAsync()
{
ManualResetEvent manualEvent = new ManualResetEvent(false);
Exception exception = null;
template.PostForMessageAsync<string>("user", "Lisa Baia",
delegate(MethodCompletedEventArgs<HttpResponseMessage<string>> args)
{
try
{
Assert.IsNull(args.Error, "Invalid response");
Assert.IsFalse(args.Cancelled, "Invalid response");
Assert.AreEqual(new Uri(new Uri(uri), "/user/3"), args.Response.Headers.Location, "Invalid location");
Assert.AreEqual(HttpStatusCode.Created, args.Response.StatusCode, "Invalid status code");
Assert.AreEqual("User id '3' created with 'Lisa Baia'", args.Response.StatusDescription, "Invalid status description");
Assert.AreEqual("3", args.Response.Body, "Invalid content");
}
catch (Exception ex)
{
exception = ex;
}
finally
{
manualEvent.Set();
}
});
manualEvent.WaitOne();
if (exception != null)
{
throw exception;
}
}
[Test]
public void DeleteAsyncWithNoAction()
{
string result = template.GetForObject<string>("users");
Assert.AreEqual("2", result, "Invalid content");
template.DeleteAsync("user/2", null);
Thread.Sleep(TimeSpan.FromSeconds(1));
result = template.GetForObject<string>("users");
Assert.AreEqual("1", result, "Invalid content");
}
[Test]
public void ExchangeForMessageAsync()
{
ManualResetEvent manualEvent = new ManualResetEvent(false);
Exception exception = null;
template.ExchangeAsync("user/1", HttpMethod.PUT, new HttpEntity("Bruno Baia"),
delegate(MethodCompletedEventArgs<HttpResponseMessage> args)
{
try
{
Assert.IsNull(args.Error, "Invalid response");
Assert.IsFalse(args.Cancelled, "Invalid response");
Assert.AreEqual(HttpStatusCode.OK, args.Response.StatusCode, "Invalid status code");
Assert.AreEqual("User id '1' updated with 'Bruno Baia'", args.Response.StatusDescription, "Invalid status description");
}
catch (Exception ex)
{
exception = ex;
}
finally
{
manualEvent.Set();
}
});
manualEvent.WaitOne();
if (exception != null)
{
throw exception;
}
}
[Test]
[ExpectedException(typeof(HttpClientErrorException),
ExpectedMessage = "The server returned 'Not Found' with the status code 404 - NotFound.")]
public void ClientErrorAsync()
{
ManualResetEvent manualEvent = new ManualResetEvent(false);
Exception exception = null;
template.ExecuteAsync<object>("clienterror", HttpMethod.GET, null, null,
delegate(MethodCompletedEventArgs<object> args)
{
try
{
Assert.IsFalse(args.Cancelled, "Invalid response");
Assert.IsNotNull(args.Error, "Invalid response");
exception = args.Error;
}
catch (Exception ex)
{
exception = ex;
}
finally
{
manualEvent.Set();
}
});
manualEvent.WaitOne();
if (exception != null)
{
throw exception;
}
}
[Test]
[ExpectedException(typeof(HttpServerErrorException),
ExpectedMessage = "The server returned 'Internal Server Error' with the status code 500 - InternalServerError.")]
public void ServerErrorAsync()
{
ManualResetEvent manualEvent = new ManualResetEvent(false);
Exception exception = null;
template.ExecuteAsync<object>("servererror", HttpMethod.GET, null, null,
delegate(MethodCompletedEventArgs<object> args)
{
try
{
Assert.IsFalse(args.Cancelled, "Invalid response");
Assert.IsNotNull(args.Error, "Invalid response");
exception = args.Error;
}
catch (Exception ex)
{
exception = ex;
}
finally
{
manualEvent.Set();
}
});
manualEvent.WaitOne();
if (exception != null)
{
throw exception;
}
}
#endregion
#region REST test service
[ServiceContract]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class TestService
{
private IDictionary<string, string> users;
public TestService()
{
users = new Dictionary<string, string>();
users.Add("1", "Bruno Baïa");
users.Add("2", "Marie Baia");
}
[OperationContract]
[WebGet(UriTemplate = "clienterror")]
public void ClientError()
{
WebOperationContext.Current.OutgoingResponse.SetStatusAsNotFound();
}
[OperationContract]
[WebGet(UriTemplate = "servererror")]
public void ServerError()
{
WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.InternalServerError;
}
[OperationContract]
[WebInvoke(UriTemplate = "allow", Method = "OPTIONS")]
public void Allow()
{
WebOperationContext.Current.OutgoingResponse.Headers[HttpResponseHeader.Allow] = "GET, HEAD, PUT";
}
[OperationContract]
[WebInvoke(UriTemplate = "head", Method = "HEAD")]
public void Head()
{
WebOperationContext.Current.OutgoingResponse.Headers["MyHeader"] = "MyValue";
}
[OperationContract]
[WebGet(UriTemplate = "user/{id}")]
public Stream GetUser(string id)
{
WebOperationContext context = WebOperationContext.Current;
if (!users.ContainsKey(id))
{
context.OutgoingResponse.SetStatusAsNotFound(String.Format("User with id '{0}' not found", id));
return null;
}
return CreateTextResponse(context, users[id]);
}
[OperationContract]
[WebGet(UriTemplate = "users")]
public Stream GetUsersCount()
{
WebOperationContext context = WebOperationContext.Current;
return CreateTextResponse(context, users.Count.ToString());
}
[OperationContract]
[WebGet(UriTemplate = "nothing")]
public void GetNothing()
{
WebOperationContext.Current.OutgoingResponse.SuppressEntityBody = true;
}
[OperationContract]
[WebInvoke(UriTemplate = "user", Method = "POST")]
public Stream Post(Stream stream)
{
WebOperationContext context = WebOperationContext.Current;
UriTemplateMatch match = context.IncomingRequest.UriTemplateMatch;
UriTemplate template = new UriTemplate("/user/{id}");
MediaType mediaType = MediaType.Parse(context.IncomingRequest.ContentType);
Encoding encoding = (mediaType == null) ? Encoding.UTF8 : Encoding.GetEncoding(mediaType.CharSet);
string id = (users.Count + 1).ToString(); // generate new ID
string name;
using (StreamReader reader = new StreamReader(stream, encoding))
{
name = reader.ReadToEnd();
}
if (String.IsNullOrEmpty(name))
{
context.OutgoingResponse.StatusCode = HttpStatusCode.BadRequest;
context.OutgoingResponse.StatusDescription = "Content cannot be null or empty";
return CreateTextResponse(context, "");
}
users.Add(id, name);
Uri uri = template.BindByPosition(match.BaseUri, id);
context.OutgoingResponse.SetStatusAsCreated(uri);
context.OutgoingResponse.StatusDescription = String.Format("User id '{0}' created with '{1}'", id, name);
return CreateTextResponse(context, id);
}
[OperationContract]
[WebInvoke(UriTemplate = "user/{id}", Method = "PUT")]
public void Update(string id, Stream stream)
{
WebOperationContext context = WebOperationContext.Current;
if (!users.ContainsKey(id))
{
context.OutgoingResponse.StatusCode = HttpStatusCode.BadRequest;
context.OutgoingResponse.StatusDescription = String.Format("User id '{0}' does not exist", id);
return;
}
MediaType mediaType = MediaType.Parse(context.IncomingRequest.ContentType);
string name;
using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding(mediaType.CharSet)))
{
name = reader.ReadToEnd();
}
users[id] = name;
context.OutgoingResponse.StatusCode = HttpStatusCode.OK;
context.OutgoingResponse.StatusDescription = String.Format("User id '{0}' updated with '{1}'", id, name);
}
[OperationContract]
[WebInvoke(UriTemplate = "user/{id}", Method = "DELETE")]
public void Delete(string id)
{
WebOperationContext context = WebOperationContext.Current;
if (!users.ContainsKey(id))
{
context.OutgoingResponse.StatusCode = HttpStatusCode.BadRequest;
context.OutgoingResponse.StatusDescription = String.Format("User id '{0}' does not exist", id);
return;
}
users.Remove(id);
context.OutgoingResponse.StatusCode = HttpStatusCode.OK;
context.OutgoingResponse.StatusDescription = String.Format("User id '{0}' have been removed", id);
}
private Stream CreateTextResponse(WebOperationContext context, string text)
{
context.OutgoingResponse.ContentType = "text/plain; charset=utf-8";
return new MemoryStream(Encoding.UTF8.GetBytes(text));
}
}
#endregion
}
}
#endif

View File

@@ -1,644 +0,0 @@
#region License
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System;
using System.IO;
using System.Net;
using System.Collections.Generic;
using Spring.Http.Client;
using Spring.Http.Converters;
using NUnit.Framework;
using Rhino.Mocks;
namespace Spring.Http.Rest
{
/// <summary>
/// Unit tests for the RestTemplate class.
/// </summary>
/// <author>Arjen Poutsma</author>
/// <author>Bruno Baia (.NET)</author>
[TestFixture]
public class RestTemplateTests
{
#region Logging
private static readonly Common.Logging.ILog LOG = Common.Logging.LogManager.GetLogger(typeof(RestTemplateTests));
#endregion
private MockRepository mocks;
private RestTemplate template;
private IClientHttpRequestFactory requestFactory;
private IClientHttpRequest request;
private IClientHttpResponse response;
private IResponseErrorHandler errorHandler;
private IHttpMessageConverter converter;
[SetUp]
public void SetUp()
{
mocks = new MockRepository();
requestFactory = mocks.CreateMock<IClientHttpRequestFactory>();
request = mocks.CreateMock<IClientHttpRequest>();
response = mocks.CreateMock<IClientHttpResponse>();
errorHandler = mocks.CreateMock<IResponseErrorHandler>();
converter = mocks.CreateMock<IHttpMessageConverter>();
IList<IHttpMessageConverter> messageConverters = new List<IHttpMessageConverter>(1);
messageConverters.Add(converter);
template = new RestTemplate();
template.RequestFactory = requestFactory;
template.MessageConverters = messageConverters;
template.ErrorHandler = errorHandler;
}
[TearDown]
public void TearDown()
{
mocks.VerifyAll();
}
[Test]
public void VarArgsTemplateVariables()
{
Expect.Call<IClientHttpRequest>(requestFactory.CreateRequest(new Uri("http://example.com/hotels/42/bookings/21"), HttpMethod.GET))
.Return(request);
ExpectGetResponse();
Expect.Call<bool>(errorHandler.HasError(response)).Return(false);
mocks.ReplayAll();
template.Execute<object>("http://example.com/hotels/{hotel}/bookings/{booking}", HttpMethod.GET, null, null, "42", "21");
}
[Test]
public void DictionaryTemplateVariables()
{
Expect.Call<IClientHttpRequest>(requestFactory.CreateRequest(new Uri("http://example.com/hotels/42/bookings/21"), HttpMethod.GET))
.Return(request);
ExpectGetResponse();
Expect.Call<bool>(errorHandler.HasError(response)).Return(false);
mocks.ReplayAll();
IDictionary<string, string> variables = new Dictionary<string, string>();
variables.Add("booking", "41");
variables.Add("hotel", "42");
template.Execute<object>("http://example.com/hotels/{hotel}/bookings/{booking}", HttpMethod.GET, null, null, "42", "21");
}
[Test]
public void BaseAddressTemplate()
{
Expect.Call<IClientHttpRequest>(requestFactory.CreateRequest(new Uri("http://example.com/hotels/42/bookings/21"), HttpMethod.GET))
.Return(request);
ExpectGetResponse();
Expect.Call<bool>(errorHandler.HasError(response)).Return(false);
mocks.ReplayAll();
template.BaseAddress = new Uri("http://example.com");
template.Execute<object>("hotels/{hotel}/bookings/{booking}", HttpMethod.GET, null, null, "42", "21");
}
[Test]
[ExpectedException(typeof(HttpServerErrorException), ExpectedMessage = "The server returned 'InternalServerError' with the status code 500.")]
public void ErrorHandling()
{
Expect.Call<IClientHttpRequest>(requestFactory.CreateRequest(new Uri("http://example.com"), HttpMethod.GET))
.Return(request);
ExpectGetResponse();
Expect.Call<bool>(errorHandler.HasError(response)).Return(true);
Expect.Call(delegate() { errorHandler.HandleError(response); }).Throw(new HttpServerErrorException(HttpStatusCode.InternalServerError));
mocks.ReplayAll();
template.Execute<object>("http://example.com", HttpMethod.GET, null, null);
}
[Test]
public void GetForObject()
{
Expect.Call<bool>(converter.CanRead(typeof(string), null)).Return(true);
MediaType textPlain = new MediaType("text", "plain");
IList<MediaType> mediaTypes = new List<MediaType>(1);
mediaTypes.Add(textPlain);
Expect.Call<IList<MediaType>>(converter.SupportedMediaTypes).Return(mediaTypes);
Expect.Call<IClientHttpRequest>(requestFactory.CreateRequest(new Uri("http://example.com"), HttpMethod.GET)).Return(request);
HttpHeaders requestHeaders = new HttpHeaders();
Expect.Call<HttpHeaders>(request.Headers).Return(requestHeaders).Repeat.Any();
ExpectGetResponse();
Expect.Call<bool>(errorHandler.HasError(response)).Return(false);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.ContentType = textPlain;
Expect.Call<HttpHeaders>(response.Headers).Return(responseHeaders).Repeat.Any();
Expect.Call<bool>(converter.CanRead(typeof(string), textPlain)).Return(true);
String expected = "Hello World";
Expect.Call<string>(converter.Read<string>(response)).Return(expected);
mocks.ReplayAll();
string result = template.GetForObject<string>("http://example.com");
Assert.AreEqual(expected, result, "Invalid GET result");
Assert.AreEqual(textPlain.ToString(), requestHeaders.GetSingleValue("Accept"), "Invalid Accept header");
}
[Test]
[ExpectedException(typeof(RestClientException),
ExpectedMessage = "Could not extract response: no suitable HttpMessageConverter found for response type [System.String] and content type [bar/baz]")]
public void GetUnsupportedMediaType()
{
Expect.Call<bool>(converter.CanRead(typeof(string), null)).Return(true);
MediaType textPlain = new MediaType("foo", "bar");
IList<MediaType> mediaTypes = new List<MediaType>(1);
mediaTypes.Add(textPlain);
Expect.Call<IList<MediaType>>(converter.SupportedMediaTypes).Return(mediaTypes);
Expect.Call<IClientHttpRequest>(requestFactory.CreateRequest(new Uri("http://example.com/resource"), HttpMethod.GET)).Return(request);
HttpHeaders requestHeaders = new HttpHeaders();
Expect.Call<HttpHeaders>(request.Headers).Return(requestHeaders).Repeat.Any();
ExpectGetResponse();
Expect.Call<bool>(errorHandler.HasError(response)).Return(false);
HttpHeaders responseHeaders = new HttpHeaders();
MediaType contentType = new MediaType("bar", "baz");
responseHeaders.ContentType = contentType;
Expect.Call<HttpHeaders>(response.Headers).Return(responseHeaders).Repeat.Any();
Expect.Call<bool>(converter.CanRead(typeof(string), contentType)).Return(false);
mocks.ReplayAll();
template.GetForObject<string>("http://example.com/{p}", "resource");
}
[Test]
public void GetForMessage()
{
Expect.Call<bool>(converter.CanRead(typeof(string), null)).Return(true);
MediaType textPlain = new MediaType("text", "plain");
IList<MediaType> mediaTypes = new List<MediaType>(1);
mediaTypes.Add(textPlain);
Expect.Call<IList<MediaType>>(converter.SupportedMediaTypes).Return(mediaTypes);
Expect.Call<IClientHttpRequest>(requestFactory.CreateRequest(new Uri("http://example.com"), HttpMethod.GET)).Return(request);
HttpHeaders requestHeaders = new HttpHeaders();
Expect.Call<HttpHeaders>(request.Headers).Return(requestHeaders).Repeat.Any();
ExpectGetResponse();
Expect.Call<bool>(errorHandler.HasError(response)).Return(false);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.ContentType = textPlain;
Expect.Call<HttpHeaders>(response.Headers).Return(responseHeaders).Repeat.Any();
Expect.Call<bool>(converter.CanRead(typeof(string), textPlain)).Return(true);
String expected = "Hello World";
Expect.Call<string>(converter.Read<string>(response)).Return(expected);
Expect.Call<HttpStatusCode>(response.StatusCode).Return(HttpStatusCode.OK);
Expect.Call<string>(response.StatusDescription).Return("OK");
mocks.ReplayAll();
HttpResponseMessage<String> result = template.GetForMessage<string>("http://example.com");
Assert.AreEqual(expected, result.Body, "Invalid GET result");
Assert.AreEqual(textPlain, result.Headers.ContentType, "Invalid Content-Type");
Assert.AreEqual(textPlain.ToString(), requestHeaders.GetSingleValue("Accept"), "Invalid Accept header");
Assert.AreEqual(HttpStatusCode.OK, result.StatusCode, "Invalid status code");
Assert.AreEqual("OK", result.StatusDescription, "Invalid status description");
mocks.ReplayAll();
}
[Test]
public void HeadForHeaders()
{
Expect.Call<IClientHttpRequest>(requestFactory.CreateRequest(new Uri("http://example.com"), HttpMethod.HEAD)).Return(request);
ExpectGetResponse();
Expect.Call<bool>(errorHandler.HasError(response)).Return(false);
HttpHeaders responseHeaders = new HttpHeaders();
Expect.Call<HttpHeaders>(response.Headers).Return(responseHeaders).Repeat.Any();
mocks.ReplayAll();
HttpHeaders result = template.HeadForHeaders("http://example.com");
Assert.AreSame(responseHeaders, result, "Invalid headers returned");
}
[Test]
public void PostForLocation()
{
string helloWorld = "Hello World";
Expect.Call<IClientHttpRequest>(requestFactory.CreateRequest(new Uri("http://example.com"), HttpMethod.POST)).Return(request);
Expect.Call<bool>(converter.CanWrite(typeof(string), null)).Return(true);
converter.Write(helloWorld, null, request);
ExpectGetResponse();
Expect.Call<bool>(errorHandler.HasError(response)).Return(false);
HttpHeaders responseHeaders = new HttpHeaders();
Uri expected = new Uri("http://example.com/hotels");
responseHeaders.Location = expected;
Expect.Call<HttpHeaders>(response.Headers).Return(responseHeaders).Repeat.Any();
mocks.ReplayAll();
Uri result = template.PostForLocation("http://example.com", helloWorld);
Assert.AreEqual(expected, result, "Invalid POST result");
}
[Test]
public void PostForLocationMessageContentType()
{
string helloWorld = "Hello World";
Expect.Call<IClientHttpRequest>(requestFactory.CreateRequest(new Uri("http://example.com"), HttpMethod.POST)).Return(request);
MediaType contentType = new MediaType("text", "plain");
Expect.Call<bool>(converter.CanWrite(typeof(string), contentType)).Return(true);
HttpHeaders requestHeaders = new HttpHeaders();
Expect.Call<HttpHeaders>(request.Headers).Return(requestHeaders).Repeat.Any();
converter.Write(helloWorld, contentType, request);
ExpectGetResponse();
Expect.Call<bool>(errorHandler.HasError(response)).Return(false);
HttpHeaders responseHeaders = new HttpHeaders();
Uri expected = new Uri("http://example.com/hotels");
responseHeaders.Location = expected;
Expect.Call<HttpHeaders>(response.Headers).Return(responseHeaders).Repeat.Any();
mocks.ReplayAll();
HttpHeaders entityHeaders = new HttpHeaders();
entityHeaders.ContentType = contentType;
HttpEntity entity = new HttpEntity(helloWorld, entityHeaders);
Uri result = template.PostForLocation("http://example.com", entity);
Assert.AreEqual(expected, result, "Invalid POST result");
}
[Test]
public void PostForLocationMessageCustomHeader()
{
string helloWorld = "Hello World";
Expect.Call<IClientHttpRequest>(requestFactory.CreateRequest(new Uri("http://example.com"), HttpMethod.POST)).Return(request);
Expect.Call<bool>(converter.CanWrite(typeof(string), null)).Return(true);
HttpHeaders requestHeaders = new HttpHeaders();
Expect.Call<HttpHeaders>(request.Headers).Return(requestHeaders).Repeat.Any();
converter.Write(helloWorld, null, request);
ExpectGetResponse();
Expect.Call<bool>(errorHandler.HasError(response)).Return(false);
HttpHeaders responseHeaders = new HttpHeaders();
Uri expected = new Uri("http://example.com/hotels");
responseHeaders.Location = expected;
Expect.Call<HttpHeaders>(response.Headers).Return(responseHeaders).Repeat.Any();
mocks.ReplayAll();
HttpHeaders entityHeaders = new HttpHeaders();
entityHeaders.Add("MyHeader", "MyValue");
HttpEntity entity = new HttpEntity(helloWorld, entityHeaders);
Uri result = template.PostForLocation("http://example.com", entity);
Assert.AreEqual(expected, result, "Invalid POST result");
Assert.AreEqual("MyValue", requestHeaders.Get("MyHeader"), "No custom header set");
}
[Test]
public void PostForLocationNoLocation()
{
string helloWorld = "Hello World";
Expect.Call<IClientHttpRequest>(requestFactory.CreateRequest(new Uri("http://example.com"), HttpMethod.POST)).Return(request);
Expect.Call<bool>(converter.CanWrite(typeof(string), null)).Return(true);
converter.Write(helloWorld, null, request);
ExpectGetResponse();
Expect.Call<bool>(errorHandler.HasError(response)).Return(false);
HttpHeaders responseHeaders = new HttpHeaders();
Expect.Call<HttpHeaders>(response.Headers).Return(responseHeaders).Repeat.Any();
mocks.ReplayAll();
Uri result = template.PostForLocation("http://example.com", helloWorld);
Assert.IsNull(result, "Invalid POST result");
mocks.ReplayAll();
}
[Test]
public void PostForLocationNull()
{
Expect.Call<IClientHttpRequest>(requestFactory.CreateRequest(new Uri("http://example.com"), HttpMethod.POST)).Return(request);
HttpHeaders requestHeaders = new HttpHeaders();
Expect.Call<HttpHeaders>(request.Headers).Return(requestHeaders).Repeat.Any();
ExpectGetResponse();
Expect.Call<bool>(errorHandler.HasError(response)).Return(false);
HttpHeaders responseHeaders = new HttpHeaders();
Expect.Call<HttpHeaders>(response.Headers).Return(responseHeaders).Repeat.Any();
mocks.ReplayAll();
template.PostForLocation("http://example.com", null);
Assert.AreEqual(0, requestHeaders.ContentLength, "Invalid content length");
}
[Test]
public void PostForObject()
{
Expect.Call<bool>(converter.CanRead(typeof(Version), null)).Return(true);
MediaType textPlain = new MediaType("text", "plain");
IList<MediaType> mediaTypes = new List<MediaType>(1);
mediaTypes.Add(textPlain);
Expect.Call<IList<MediaType>>(converter.SupportedMediaTypes).Return(mediaTypes);
Expect.Call<IClientHttpRequest>(requestFactory.CreateRequest(new Uri("http://example.com"), HttpMethod.POST)).Return(request);
HttpHeaders requestHeaders = new HttpHeaders();
Expect.Call<HttpHeaders>(request.Headers).Return(requestHeaders).Repeat.Any();
string helloWorld = "Hello World";
Expect.Call<bool>(converter.CanWrite(typeof(string), null)).Return(true);
converter.Write(helloWorld, null, request);
ExpectGetResponse();
Expect.Call<bool>(errorHandler.HasError(response)).Return(false);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.ContentType = textPlain;
Expect.Call<HttpHeaders>(response.Headers).Return(responseHeaders).Repeat.Any();
Version expected = new Version(1, 0);
Expect.Call<bool>(converter.CanRead(typeof(Version), textPlain)).Return(true);
Expect.Call<Version>(converter.Read<Version>(response)).Return(expected);
mocks.ReplayAll();
Version result = template.PostForObject<Version>("http://example.com", helloWorld);
Assert.AreEqual(expected, result, "Invalid POST result");
Assert.AreEqual(textPlain.ToString(), requestHeaders.GetSingleValue("Accept"), "Invalid Accept header");
}
[Test]
public void PostForMessage()
{
Expect.Call<bool>(converter.CanRead(typeof(Version), null)).Return(true);
MediaType textPlain = new MediaType("text", "plain");
IList<MediaType> mediaTypes = new List<MediaType>(1);
mediaTypes.Add(textPlain);
Expect.Call<IList<MediaType>>(converter.SupportedMediaTypes).Return(mediaTypes);
Expect.Call<IClientHttpRequest>(requestFactory.CreateRequest(new Uri("http://example.com"), HttpMethod.POST)).Return(request);
HttpHeaders requestHeaders = new HttpHeaders();
Expect.Call<HttpHeaders>(request.Headers).Return(requestHeaders).Repeat.Any();
string helloWorld = "Hello World";
Expect.Call<bool>(converter.CanWrite(typeof(string), null)).Return(true);
converter.Write(helloWorld, null, request);
ExpectGetResponse();
Expect.Call<bool>(errorHandler.HasError(response)).Return(false);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.ContentType = textPlain;
Expect.Call<HttpHeaders>(response.Headers).Return(responseHeaders).Repeat.Any();
Version expected = new Version(1, 0);
Expect.Call<bool>(converter.CanRead(typeof(Version), textPlain)).Return(true);
Expect.Call<Version>(converter.Read<Version>(response)).Return(expected);
Expect.Call<HttpStatusCode>(response.StatusCode).Return(HttpStatusCode.OK);
Expect.Call<string>(response.StatusDescription).Return("OK");
mocks.ReplayAll();
HttpResponseMessage<Version> result = template.PostForMessage<Version>("http://example.com", helloWorld);
Assert.AreEqual(expected, result.Body, "Invalid POST result");
Assert.AreEqual(textPlain, result.Headers.ContentType, "Invalid Content-Type");
Assert.AreEqual(textPlain.ToString(), requestHeaders.GetSingleValue("Accept"), "Invalid Accept header");
Assert.AreEqual(HttpStatusCode.OK, result.StatusCode, "Invalid status code");
Assert.AreEqual("OK", result.StatusDescription, "Invalid status description");
}
[Test]
public void PostForMessageNoBody()
{
Expect.Call<IClientHttpRequest>(requestFactory.CreateRequest(new Uri("http://example.com"), HttpMethod.POST)).Return(request);
HttpHeaders requestHeaders = new HttpHeaders();
Expect.Call<HttpHeaders>(request.Headers).Return(requestHeaders).Repeat.Any();
string helloWorld = "Hello World";
Expect.Call<bool>(converter.CanWrite(typeof(string), null)).Return(true);
converter.Write(helloWorld, null, request);
ExpectGetResponse();
Expect.Call<bool>(errorHandler.HasError(response)).Return(false);
HttpHeaders responseHeaders = new HttpHeaders();
Expect.Call<HttpHeaders>(response.Headers).Return(responseHeaders);
Expect.Call<HttpStatusCode>(response.StatusCode).Return(HttpStatusCode.Created);
Expect.Call<string>(response.StatusDescription).Return("CREATED");
mocks.ReplayAll();
HttpResponseMessage result = template.PostForMessage("http://example.com", helloWorld);
Assert.IsNull(result.Body, "Invalid POST result");
Assert.AreEqual(HttpStatusCode.Created, result.StatusCode, "Invalid status code");
Assert.AreEqual("CREATED", result.StatusDescription, "Invalid status description");
}
[Test]
public void PostForObjectNull()
{
Expect.Call<bool>(converter.CanRead(typeof(Version), null)).Return(true);
MediaType textPlain = new MediaType("text", "plain");
IList<MediaType> mediaTypes = new List<MediaType>(1);
mediaTypes.Add(textPlain);
Expect.Call<IList<MediaType>>(converter.SupportedMediaTypes).Return(mediaTypes);
Expect.Call<IClientHttpRequest>(requestFactory.CreateRequest(new Uri("http://example.com"), HttpMethod.POST)).Return(request);
HttpHeaders requestHeaders = new HttpHeaders();
Expect.Call<HttpHeaders>(request.Headers).Return(requestHeaders).Repeat.Any();
ExpectGetResponse();
Expect.Call<bool>(errorHandler.HasError(response)).Return(false);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.ContentType = textPlain;
Expect.Call<HttpHeaders>(response.Headers).Return(responseHeaders).Repeat.Any();
Expect.Call<bool>(converter.CanRead(typeof(Version), textPlain)).Return(true);
Expect.Call<Version>(converter.Read<Version>(response)).Return(null);
mocks.ReplayAll();
Version result = template.PostForObject<Version>("http://example.com", null);
Assert.IsNull(result, "Invalid POST result");
Assert.AreEqual(textPlain.ToString(), requestHeaders.GetSingleValue("Accept"), "Invalid Accept header");
Assert.AreEqual(0, requestHeaders.ContentLength, "Invalid content length");
}
[Test]
public void PostForEntityNull()
{
Expect.Call<bool>(converter.CanRead(typeof(Version), null)).Return(true);
MediaType textPlain = new MediaType("text", "plain");
IList<MediaType> mediaTypes = new List<MediaType>(1);
mediaTypes.Add(textPlain);
Expect.Call<IList<MediaType>>(converter.SupportedMediaTypes).Return(mediaTypes);
Expect.Call<IClientHttpRequest>(requestFactory.CreateRequest(new Uri("http://example.com"), HttpMethod.POST)).Return(request);
HttpHeaders requestHeaders = new HttpHeaders();
Expect.Call<HttpHeaders>(request.Headers).Return(requestHeaders).Repeat.Any();
ExpectGetResponse();
Expect.Call<bool>(errorHandler.HasError(response)).Return(false);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.ContentType = textPlain;
Expect.Call<HttpHeaders>(response.Headers).Return(responseHeaders).Repeat.Any();
Expect.Call<bool>(converter.CanRead(typeof(Version), textPlain)).Return(true);
Expect.Call<Version>(converter.Read<Version>(response)).Return(null);
Expect.Call<HttpStatusCode>(response.StatusCode).Return(HttpStatusCode.OK);
Expect.Call<string>(response.StatusDescription).Return("OK");
mocks.ReplayAll();
HttpResponseMessage<Version> result = template.PostForMessage<Version>("http://example.com", null);
Assert.IsNull(result.Body, "Invalid POST result");
Assert.AreEqual(textPlain, result.Headers.ContentType, "Invalid Content-Type");
Assert.AreEqual(textPlain.ToString(), requestHeaders.GetSingleValue("Accept"), "Invalid Accept header");
Assert.AreEqual(0, requestHeaders.ContentLength, "Invalid content length");
Assert.AreEqual(HttpStatusCode.OK, result.StatusCode, "Invalid status code");
Assert.AreEqual("OK", result.StatusDescription, "Invalid status description");
}
[Test]
public void Put()
{
Expect.Call<bool>(converter.CanWrite(typeof(string), null)).Return(true);
Expect.Call<IClientHttpRequest>(requestFactory.CreateRequest(new Uri("http://example.com"), HttpMethod.PUT)).Return(request);
string helloWorld = "Hello World";
converter.Write(helloWorld, null, request);
ExpectGetResponse();
Expect.Call<bool>(errorHandler.HasError(response)).Return(false);
mocks.ReplayAll();
template.Put("http://example.com", helloWorld);
}
[Test]
public void PutNull()
{
Expect.Call<IClientHttpRequest>(requestFactory.CreateRequest(new Uri("http://example.com"), HttpMethod.PUT)).Return(request);
HttpHeaders requestHeaders = new HttpHeaders();
Expect.Call<HttpHeaders>(request.Headers).Return(requestHeaders).Repeat.Any();
ExpectGetResponse();
Expect.Call<bool>(errorHandler.HasError(response)).Return(false);
mocks.ReplayAll();
template.Put("http://example.com", null);
Assert.AreEqual(0, requestHeaders.ContentLength, "Invalid content length");
}
[Test]
public void Delete()
{
Expect.Call<IClientHttpRequest>(requestFactory.CreateRequest(new Uri("http://example.com"), HttpMethod.DELETE)).Return(request);
ExpectGetResponse();
Expect.Call<bool>(errorHandler.HasError(response)).Return(false);
mocks.ReplayAll();
template.Delete("http://example.com");
}
[Test]
public void OptionsForAllow()
{
Expect.Call<IClientHttpRequest>(requestFactory.CreateRequest(new Uri("http://example.com"), HttpMethod.OPTIONS)).Return(request);
ExpectGetResponse();
Expect.Call<bool>(errorHandler.HasError(response)).Return(false);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.Add("Allow", "GET");
responseHeaders.Add("Allow", "POST");
Expect.Call<HttpHeaders>(response.Headers).Return(responseHeaders).Repeat.Any();
mocks.ReplayAll();
IList<HttpMethod> result = template.OptionsForAllow("http://example.com");
Assert.AreEqual(2, result.Count, "Invalid OPTIONS result");
Assert.IsTrue(result.Contains(HttpMethod.GET), "Invalid OPTIONS result");
Assert.IsTrue(result.Contains(HttpMethod.POST), "Invalid OPTIONS result");
}
//[Test]
//public void ioException() {
// Expect.Call(converter.canRead(String.class, null)).andReturn(true);
// MediaType mediaType = new MediaType("foo", "bar");
// Expect.Call(converter.getSupportedMediaTypes()).andReturn(Collections.singletonList(mediaType));
// Expect.Call(requestFactory.createRequest(new URI("http://example.com/resource"), HttpMethod.GET)).andReturn(request);
// Expect.Call(request.getHeaders()).andReturn(new HttpHeaders());
// Expect.Call(request.execute()).andThrow(new IOException());
// mocks.ReplayAll();
// try {
// template.getForObject("http://example.com/resource", String.class);
// fail("RestClientException expected");
// }
// catch (ResourceAccessException ex) {
// // expected
// }
// mocks.ReplayAll();
//}
[Test]
public void Exchange()
{
Expect.Call<bool>(converter.CanRead(typeof(Version), null)).Return(true);
MediaType textPlain = new MediaType("text", "plain");
IList<MediaType> mediaTypes = new List<MediaType>(1);
mediaTypes.Add(textPlain);
Expect.Call<IList<MediaType>>(converter.SupportedMediaTypes).Return(mediaTypes);
Expect.Call<IClientHttpRequest>(requestFactory.CreateRequest(new Uri("http://example.com"), HttpMethod.POST)).Return(request);
HttpHeaders requestHeaders = new HttpHeaders();
Expect.Call<HttpHeaders>(request.Headers).Return(requestHeaders).Repeat.Any();
string helloWorld = "Hello World";
Expect.Call<bool>(converter.CanWrite(typeof(string), null)).Return(true);
converter.Write(helloWorld, null, request);
ExpectGetResponse();
Expect.Call<bool>(errorHandler.HasError(response)).Return(false);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.ContentType = textPlain;
Expect.Call<HttpHeaders>(response.Headers).Return(responseHeaders).Repeat.Any();
Version expected = new Version(1, 0);
Expect.Call<bool>(converter.CanRead(typeof(Version), textPlain)).Return(true);
Expect.Call<Version>(converter.Read<Version>(response)).Return(expected);
Expect.Call<HttpStatusCode>(response.StatusCode).Return(HttpStatusCode.OK);
Expect.Call<string>(response.StatusDescription).Return("OK");
mocks.ReplayAll();
HttpHeaders requestMessageHeaders = new HttpHeaders();
requestMessageHeaders.Add("MyHeader", "MyValue");
HttpEntity requestEntity = new HttpEntity(helloWorld, requestMessageHeaders);
HttpResponseMessage<Version> result = template.Exchange<Version>("http://example.com", HttpMethod.POST, requestEntity);
Assert.AreEqual(expected, result.Body, "Invalid POST result");
Assert.AreEqual(textPlain, result.Headers.ContentType, "Invalid Content-Type");
Assert.AreEqual(textPlain.ToString(), requestHeaders.GetSingleValue("Accept"), "Invalid Accept header");
Assert.AreEqual("MyValue", requestHeaders.Get("MyHeader"), "No custom header set");
Assert.AreEqual(HttpStatusCode.OK, result.StatusCode, "Invalid status code");
Assert.AreEqual("OK", result.StatusDescription, "Invalid status description");
}
#region Utility methods
private void ExpectGetResponse()
{
Expect.Call<IClientHttpResponse>(request.Execute()).Return(response);
#region Instrumentation
if (LOG.IsDebugEnabled)
{
Expect.Call<HttpStatusCode>(response.StatusCode).Return(HttpStatusCode.OK);
Expect.Call<string>(response.StatusDescription).Return("OK");
}
#endregion
Expect.Call(response.Dispose);
}
#endregion
}
}

View File

@@ -1,136 +0,0 @@
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">
<PropertyGroup>
<ProjectType>Local</ProjectType>
<ProductVersion>8.0.50727</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{9437475B-3897-A399-46BF-45F04CEE1821}</ProjectGuid>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ApplicationIcon>
</ApplicationIcon>
<AssemblyKeyContainerName>
</AssemblyKeyContainerName>
<AssemblyName>Spring.Http.Tests</AssemblyName>
<AssemblyOriginatorKeyFile>
</AssemblyOriginatorKeyFile>
<DefaultClientScript>JScript</DefaultClientScript>
<DefaultHTMLPageLayout>Grid</DefaultHTMLPageLayout>
<DefaultTargetSchema>IE50</DefaultTargetSchema>
<DelaySign>false</DelaySign>
<OutputType>Library</OutputType>
<RootNamespace>Spring</RootNamespace>
<RunPostBuildEvent>OnBuildSuccess</RunPostBuildEvent>
<StartupObject>
</StartupObject>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<OutputPath>..\..\..\build\VS.Net.2005\Spring.Http.Tests\Debug\</OutputPath>
<AllowUnsafeBlocks>false</AllowUnsafeBlocks>
<BaseAddress>285212672</BaseAddress>
<CheckForOverflowUnderflow>false</CheckForOverflowUnderflow>
<ConfigurationOverrideFile>
</ConfigurationOverrideFile>
<DefineConstants>TRACE;DEBUG;NET_2_0</DefineConstants>
<DocumentationFile>
</DocumentationFile>
<DebugSymbols>true</DebugSymbols>
<FileAlignment>4096</FileAlignment>
<NoStdLib>false</NoStdLib>
<NoWarn>
</NoWarn>
<Optimize>false</Optimize>
<RegisterForComInterop>false</RegisterForComInterop>
<RemoveIntegerChecks>false</RemoveIntegerChecks>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<WarningLevel>4</WarningLevel>
<DebugType>full</DebugType>
<ErrorReport>prompt</ErrorReport>
<UseVSHostingProcess>true</UseVSHostingProcess>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<OutputPath>..\..\..\build\VS.Net.2005\Spring.Http.Tests\Release\</OutputPath>
<AllowUnsafeBlocks>false</AllowUnsafeBlocks>
<BaseAddress>285212672</BaseAddress>
<CheckForOverflowUnderflow>false</CheckForOverflowUnderflow>
<ConfigurationOverrideFile>
</ConfigurationOverrideFile>
<DefineConstants>TRACE;NET_2_0</DefineConstants>
<DocumentationFile>
</DocumentationFile>
<DebugSymbols>false</DebugSymbols>
<FileAlignment>4096</FileAlignment>
<NoStdLib>false</NoStdLib>
<NoWarn>
</NoWarn>
<Optimize>true</Optimize>
<RegisterForComInterop>false</RegisterForComInterop>
<RemoveIntegerChecks>false</RemoveIntegerChecks>
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
<WarningLevel>4</WarningLevel>
<DebugType>none</DebugType>
<ErrorReport>prompt</ErrorReport>
</PropertyGroup>
<ItemGroup>
<Reference Include="Common.Logging, Version=1.2.0.0, Culture=neutral, PublicKeyToken=af08829b84f0328e">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\lib\Net\2.0\Common.Logging.dll</HintPath>
</Reference>
<Reference Include="nunit.framework">
<Name>nunit.framework</Name>
<HintPath>..\..\..\lib\Net\2.0\nunit.framework.dll</HintPath>
</Reference>
<Reference Include="Rhino.Mocks, Version=3.4.0.0, Culture=neutral, PublicKeyToken=0b3305902db7183f, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\lib\Net\2.0\Rhino.Mocks.dll</HintPath>
</Reference>
<Reference Include="System">
<Name>System</Name>
</Reference>
<Reference Include="System.XML" />
</ItemGroup>
<ItemGroup>
<Compile Include="AssemblyInfo.cs" />
<Compile Include="Http\Client\AbstractClientHttpRequestFactoryIntegrationTests.cs" />
<Compile Include="Http\Client\WebClientHttpRequestFactoryIntegrationTests.cs" />
<Compile Include="Http\Converters\ByteArrayHttpMessageConverterTests.cs" />
<Compile Include="Http\Converters\FileInfoHttpMessageConverterTests.cs" />
<Compile Include="Http\Converters\FormHttpMessageConverterTests.cs" />
<Compile Include="Http\Converters\Feed\Atom10FeedHttpMessageConverterTests.cs" />
<Compile Include="Http\Converters\Feed\FeedHttpMessageConverterIntegrationTests.cs" />
<Compile Include="Http\Converters\Feed\Rss20FeedHttpMessageConverterTests.cs" />
<Compile Include="Http\Converters\Json\JsonHttpMessageConverterIntegrationTests.cs" />
<Compile Include="Http\Converters\Json\JsonHttpMessageConverterTests.cs" />
<Compile Include="Http\Converters\StringHttpMessageConverterTests.cs" />
<Compile Include="Http\Converters\Xml\DataContractHttpMessageConverterTests.cs" />
<Compile Include="Http\Converters\Xml\XElementHttpMessageConverterTests.cs" />
<Compile Include="Http\Converters\Xml\XmlDocumentHttpMessageConverterTests.cs" />
<Compile Include="Http\Converters\Xml\XmlHttpMessageConverterIntegrationTests.cs" />
<Compile Include="Http\Converters\Xml\XmlSerializableHttpMessageConverterTests.cs" />
<Compile Include="Http\MockHttpOuputMessage.cs" />
<Compile Include="Http\HttpHeadersTests.cs" />
<Compile Include="Http\MediaTypeTests.cs" />
<Compile Include="Http\MockHttpInputMessage.cs" />
<Compile Include="Http\Rest\HttpStatusCodeExceptionTests.cs" />
<Compile Include="Http\Rest\RestTemplateIntegrationTests.cs" />
<Compile Include="Util\SerializationTestUtils.cs" />
<Compile Include="Util\UriTemplateTests.cs" />
<Compile Include="Http\Rest\RestTemplateTests.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\src\Spring\Spring.Http\Spring.Http.2005.csproj">
<Project>{EE04EC0F-4B1F-1D13-B30F-00FAC04F79BC}</Project>
<Name>Spring.Http.2005</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<Content Include="Spring.Http.Tests.dll.config" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<PropertyGroup>
<PreBuildEvent>
</PreBuildEvent>
<PostBuildEvent>echo "Copying .xml files for tests"
xcopy "$(ProjectDir)Data" ..\..\..\..\build\VS.Net.2005\Spring.Http.Tests\$(ConfigurationName)\ /y /s /q /d
xcopy "$(ProjectDir)$(TargetFileName).config" ..\..\..\..\build\VS.Net.2005\Spring.Http.Tests\$(ConfigurationName)\ /y /s /q</PostBuildEvent>
</PropertyGroup>
</Project>

View File

@@ -1,79 +0,0 @@
<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>9.0.30729</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{AEA0D437-A442-4381-B682-5873D66DB72C}</ProjectGuid>
<ProjectTypeGuids>{A1591282-1198-4647-A2B1-27E5FF5F6F3B};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Spring</RootNamespace>
<AssemblyName>Spring.Http.Tests</AssemblyName>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<SilverlightApplication>false</SilverlightApplication>
<ValidateXaml>true</ValidateXaml>
<ThrowErrorsInValidation>true</ThrowErrorsInValidation>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>..\..\..\build\VS.Net.2008-SL\Spring.Http.Tests\Debug\</OutputPath>
<DefineConstants>TRACE;DEBUG;SILVERLIGHT;SILVERLIGHT_3</DefineConstants>
<NoStdLib>true</NoStdLib>
<NoConfig>true</NoConfig>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>..\..\..\build\VS.Net.2008-SL\Spring.Http.Tests\Release\</OutputPath>
<DefineConstants>TRACE;SILVERLIGHT;SILVERLIGHT_3</DefineConstants>
<NoStdLib>true</NoStdLib>
<NoConfig>true</NoConfig>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System.Windows" />
<Reference Include="mscorlib" />
<Reference Include="system" />
<Reference Include="System.Core" />
<Reference Include="System.Xml" />
<Reference Include="System.Net" />
<Reference Include="System.Windows.Browser" />
</ItemGroup>
<ItemGroup>
<Compile Include="AssemblyInfo.cs" />
<Compile Include="Http\Converters\Feed\FeedHttpMessageConverterIntegrationTests.cs" />
<Compile Include="Http\Converters\Json\JsonHttpMessageConverterIntegrationTests.cs" />
<Compile Include="Http\Converters\Xml\XmlHttpMessageConverterIntegrationTests.cs" />
<Compile Include="Http\Rest\RestTemplateIntegrationTests.cs" />
</ItemGroup>
<ItemGroup>
<None Include="Spring.Http.Tests.dll.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\src\Spring\Spring.Http\Spring.Http.2008-SL.csproj">
<Project>{5A955F0B-EEC7-427C-9E6B-A26B8B51558D}</Project>
<Name>Spring.Http.2008-SL</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\Silverlight\v3.0\Microsoft.Silverlight.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
<ProjectExtensions>
<VisualStudio>
<FlavorProperties GUID="{A1591282-1198-4647-A2B1-27E5FF5F6F3B}">
<SilverlightProjectProperties />
</FlavorProperties>
</VisualStudio>
</ProjectExtensions>
</Project>

View File

@@ -1,157 +0,0 @@
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">
<PropertyGroup>
<ProjectType>Local</ProjectType>
<ProductVersion>9.0.30729</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{F04CEE18-3897-A399-46BF-459437475B21}</ProjectGuid>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ApplicationIcon>
</ApplicationIcon>
<AssemblyKeyContainerName>
</AssemblyKeyContainerName>
<AssemblyName>Spring.Http.Tests</AssemblyName>
<AssemblyOriginatorKeyFile>
</AssemblyOriginatorKeyFile>
<DefaultClientScript>JScript</DefaultClientScript>
<DefaultHTMLPageLayout>Grid</DefaultHTMLPageLayout>
<DefaultTargetSchema>IE50</DefaultTargetSchema>
<DelaySign>false</DelaySign>
<OutputType>Library</OutputType>
<RootNamespace>Spring</RootNamespace>
<RunPostBuildEvent>OnBuildSuccess</RunPostBuildEvent>
<StartupObject>
</StartupObject>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<OutputPath>..\..\..\build\VS.Net.2008\Spring.Http.Tests\Debug\</OutputPath>
<AllowUnsafeBlocks>false</AllowUnsafeBlocks>
<BaseAddress>285212672</BaseAddress>
<CheckForOverflowUnderflow>false</CheckForOverflowUnderflow>
<ConfigurationOverrideFile>
</ConfigurationOverrideFile>
<DefineConstants>TRACE;DEBUG;NET_2_0;NET_3_0;NET_3_5</DefineConstants>
<DocumentationFile>
</DocumentationFile>
<DebugSymbols>true</DebugSymbols>
<FileAlignment>4096</FileAlignment>
<NoStdLib>false</NoStdLib>
<NoWarn>
</NoWarn>
<Optimize>false</Optimize>
<RegisterForComInterop>false</RegisterForComInterop>
<RemoveIntegerChecks>false</RemoveIntegerChecks>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<WarningLevel>4</WarningLevel>
<DebugType>full</DebugType>
<ErrorReport>prompt</ErrorReport>
<UseVSHostingProcess>true</UseVSHostingProcess>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<OutputPath>..\..\..\build\VS.Net.2008\Spring.Http.Tests\Release\</OutputPath>
<AllowUnsafeBlocks>false</AllowUnsafeBlocks>
<BaseAddress>285212672</BaseAddress>
<CheckForOverflowUnderflow>false</CheckForOverflowUnderflow>
<ConfigurationOverrideFile>
</ConfigurationOverrideFile>
<DefineConstants>TRACE;NET_2_0;NET_3_0;NET_3_5</DefineConstants>
<DocumentationFile>
</DocumentationFile>
<DebugSymbols>false</DebugSymbols>
<FileAlignment>4096</FileAlignment>
<NoStdLib>false</NoStdLib>
<NoWarn>
</NoWarn>
<Optimize>true</Optimize>
<RegisterForComInterop>false</RegisterForComInterop>
<RemoveIntegerChecks>false</RemoveIntegerChecks>
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
<WarningLevel>4</WarningLevel>
<DebugType>none</DebugType>
<ErrorReport>prompt</ErrorReport>
</PropertyGroup>
<ItemGroup>
<Reference Include="Common.Logging, Version=1.2.0.0, Culture=neutral, PublicKeyToken=af08829b84f0328e">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\lib\Net\2.0\Common.Logging.dll</HintPath>
</Reference>
<Reference Include="nunit.framework">
<Name>nunit.framework</Name>
<HintPath>..\..\..\lib\Net\2.0\nunit.framework.dll</HintPath>
</Reference>
<Reference Include="Rhino.Mocks, Version=3.4.0.0, Culture=neutral, PublicKeyToken=0b3305902db7183f, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\lib\Net\2.0\Rhino.Mocks.dll</HintPath>
</Reference>
<Reference Include="System">
<Name>System</Name>
</Reference>
<Reference Include="System.Core">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.IdentityModel">
<RequiredTargetFramework>3.0</RequiredTargetFramework>
</Reference>
<Reference Include="System.Runtime.Serialization">
<RequiredTargetFramework>3.0</RequiredTargetFramework>
</Reference>
<Reference Include="System.ServiceModel">
<RequiredTargetFramework>3.0</RequiredTargetFramework>
</Reference>
<Reference Include="System.ServiceModel.Web">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.XML" />
<Reference Include="System.Xml.Linq">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="AssemblyInfo.cs" />
<Compile Include="Http\Client\AbstractClientHttpRequestFactoryIntegrationTests.cs" />
<Compile Include="Http\Client\WebClientHttpRequestFactoryIntegrationTests.cs" />
<Compile Include="Http\Converters\ByteArrayHttpMessageConverterTests.cs" />
<Compile Include="Http\Converters\FileInfoHttpMessageConverterTests.cs" />
<Compile Include="Http\Converters\Feed\Atom10FeedHttpMessageConverterTests.cs" />
<Compile Include="Http\Converters\Feed\FeedHttpMessageConverterIntegrationTests.cs" />
<Compile Include="Http\Converters\Feed\Rss20FeedHttpMessageConverterTests.cs" />
<Compile Include="Http\Converters\FormHttpMessageConverterTests.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="Http\Converters\Json\JsonHttpMessageConverterIntegrationTests.cs" />
<Compile Include="Http\Converters\Json\JsonHttpMessageConverterTests.cs" />
<Compile Include="Http\Converters\StringHttpMessageConverterTests.cs" />
<Compile Include="Http\Converters\Xml\DataContractHttpMessageConverterTests.cs" />
<Compile Include="Http\Converters\Xml\XElementHttpMessageConverterTests.cs" />
<Compile Include="Http\Converters\Xml\XmlDocumentHttpMessageConverterTests.cs" />
<Compile Include="Http\Converters\Xml\XmlHttpMessageConverterIntegrationTests.cs" />
<Compile Include="Http\Converters\Xml\XmlSerializableHttpMessageConverterTests.cs" />
<Compile Include="Http\MockHttpOuputMessage.cs" />
<Compile Include="Http\HttpHeadersTests.cs" />
<Compile Include="Http\MediaTypeTests.cs" />
<Compile Include="Http\MockHttpInputMessage.cs" />
<Compile Include="Http\Rest\HttpStatusCodeExceptionTests.cs" />
<Compile Include="Http\Rest\RestTemplateIntegrationTests.cs" />
<Compile Include="Util\SerializationTestUtils.cs" />
<Compile Include="Util\UriTemplateTests.cs" />
<Compile Include="Http\Rest\RestTemplateTests.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\src\Spring\Spring.Http\Spring.Http.2008.csproj">
<Project>{FAC04F79-4B1F-1D13-B30F-00EE04EC0FBC}</Project>
<Name>Spring.Http.2008</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<Content Include="Spring.Http.Tests.dll.config" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<PropertyGroup>
<PreBuildEvent>
</PreBuildEvent>
<PostBuildEvent>echo "Copying .xml files for tests"
xcopy "$(ProjectDir)Data" ..\..\..\..\build\VS.Net.2008\Spring.Http.Tests\$(ConfigurationName)\ /y /s /q /d
xcopy "$(ProjectDir)$(TargetFileName).config" ..\..\..\..\build\VS.Net.2008\Spring.Http.Tests\$(ConfigurationName)\ /y /s /q</PostBuildEvent>
</PropertyGroup>
</Project>

View File

@@ -1,94 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.50727</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{5964F3BF-D3E0-4890-955A-BD287B834B36}</ProjectGuid>
<ProjectTypeGuids>{A1591282-1198-4647-A2B1-27E5FF5F6F3B};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Spring</RootNamespace>
<AssemblyName>Spring.Http.Tests</AssemblyName>
<TargetFrameworkIdentifier>Silverlight</TargetFrameworkIdentifier>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<SilverlightVersion>$(TargetFrameworkVersion)</SilverlightVersion>
<SilverlightApplication>false</SilverlightApplication>
<ValidateXaml>true</ValidateXaml>
<ThrowErrorsInValidation>true</ThrowErrorsInValidation>
</PropertyGroup>
<!-- This property group is only here to support building this project using the
MSBuild 3.5 toolset. In order to work correctly with this older toolset, it needs
to set the TargetFrameworkVersion to v3.5 -->
<PropertyGroup Condition="'$(MSBuildToolsVersion)' == '3.5'">
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>..\..\..\build\VS.Net.2010-SL\Spring.Http.Tests\Debug\</OutputPath>
<DefineConstants>TRACE;DEBUG;SILVERLIGHT</DefineConstants>
<NoStdLib>true</NoStdLib>
<NoConfig>true</NoConfig>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>..\..\..\build\VS.Net.2010-SL\Spring.Http.Tests\Release\</OutputPath>
<DefineConstants>TRACE;SILVERLIGHT</DefineConstants>
<NoStdLib>true</NoStdLib>
<NoConfig>true</NoConfig>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="mscorlib" />
<Reference Include="System.Runtime.Serialization" />
<Reference Include="System.ServiceModel" />
<Reference Include="System.ServiceModel.Web" />
<Reference Include="System.Windows" />
<Reference Include="system" />
<Reference Include="System.Core" />
<Reference Include="System.Xml" />
<Reference Include="System.Net" />
<Reference Include="System.Windows.Browser" />
</ItemGroup>
<ItemGroup>
<Compile Include="AssemblyInfo.cs" />
<Compile Include="Http\Converters\Feed\FeedHttpMessageConverterIntegrationTests.cs" />
<Compile Include="Http\Converters\Json\JsonHttpMessageConverterIntegrationTests.cs" />
<Compile Include="Http\Converters\Xml\XmlHttpMessageConverterIntegrationTests.cs" />
<Compile Include="Http\Rest\RestTemplateIntegrationTests.cs" />
</ItemGroup>
<ItemGroup>
<None Include="Spring.Http.Tests.dll.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\src\Spring\Spring.Http\Spring.Http.2010-SL.csproj">
<Project>{01FA5AEB-20A3-42FF-B2E9-A2FE9A7236D1}</Project>
<Name>Spring.Http.2010-SL</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<Folder Include="Util\" />
</ItemGroup>
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\Silverlight\$(SilverlightVersion)\Microsoft.Silverlight.CSharp.targets" />
<ProjectExtensions>
<VisualStudio>
<FlavorProperties GUID="{A1591282-1198-4647-A2B1-27E5FF5F6F3B}">
<SilverlightProjectProperties />
</FlavorProperties>
</VisualStudio>
</ProjectExtensions>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@@ -1,75 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>10.0.20506</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{83D8AF31-6DF1-4D2F-BFD2-865E91E6976E}</ProjectGuid>
<ProjectTypeGuids>{C089C8C0-30E0-4E22-80C0-CE093F111A43};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Spring</RootNamespace>
<AssemblyName>Spring.Http.Tests</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<SilverlightVersion>$(TargetFrameworkVersion)</SilverlightVersion>
<TargetFrameworkProfile>WindowsPhone</TargetFrameworkProfile>
<TargetFrameworkIdentifier>Silverlight</TargetFrameworkIdentifier>
<SilverlightApplication>false</SilverlightApplication>
<ValidateXaml>true</ValidateXaml>
<ThrowErrorsInValidation>true</ThrowErrorsInValidation>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>..\..\..\build\VS.Net.2010-WP\Spring.Http.Tests\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE;SILVERLIGHT;WINDOWS_PHONE</DefineConstants>
<NoStdLib>true</NoStdLib>
<NoConfig>true</NoConfig>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>..\..\..\build\VS.Net.2010-WP\Spring.Http.Tests\Release\</OutputPath>
<DefineConstants>TRACE;SILVERLIGHT;WINDOWS_PHONE</DefineConstants>
<NoStdLib>true</NoStdLib>
<NoConfig>true</NoConfig>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="system" />
<Reference Include="System.Core" />
<Reference Include="System.Xml" />
<Reference Include="System.Net" />
</ItemGroup>
<ItemGroup>
<Compile Include="AssemblyInfo.cs" />
<Compile Include="Http\Converters\Feed\FeedHttpMessageConverterIntegrationTests.cs" />
<Compile Include="Http\Converters\Json\JsonHttpMessageConverterIntegrationTests.cs" />
<Compile Include="Http\Converters\Xml\XmlHttpMessageConverterIntegrationTests.cs" />
<Compile Include="Http\Rest\RestTemplateIntegrationTests.cs" />
</ItemGroup>
<ItemGroup>
<None Include="Spring.Http.Tests.dll.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\src\Spring\Spring.Http\Spring.Http.2010-WP.csproj">
<Project>{36227431-B822-461E-A7AF-651E34F23A8C}</Project>
<Name>Spring.Http.2010-WP</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildExtensionsPath)\Microsoft\Silverlight for Phone\$(TargetFrameworkVersion)\Microsoft.Silverlight.$(TargetFrameworkProfile).Overrides.targets" />
<Import Project="$(MSBuildExtensionsPath)\Microsoft\Silverlight for Phone\$(TargetFrameworkVersion)\Microsoft.Silverlight.CSharp.targets" />
<ProjectExtensions />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@@ -1,170 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
<PropertyGroup>
<ProjectType>Local</ProjectType>
<ProductVersion>9.0.30729</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{4594CEE7-3897-A3BF-9946-5B4374F01821}</ProjectGuid>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ApplicationIcon>
</ApplicationIcon>
<AssemblyKeyContainerName>
</AssemblyKeyContainerName>
<AssemblyName>Spring.Http.Tests</AssemblyName>
<AssemblyOriginatorKeyFile>
</AssemblyOriginatorKeyFile>
<DefaultClientScript>JScript</DefaultClientScript>
<DefaultHTMLPageLayout>Grid</DefaultHTMLPageLayout>
<DefaultTargetSchema>IE50</DefaultTargetSchema>
<DelaySign>false</DelaySign>
<OutputType>Library</OutputType>
<RootNamespace>Spring</RootNamespace>
<RunPostBuildEvent>OnBuildSuccess</RunPostBuildEvent>
<StartupObject>
</StartupObject>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileUpgradeFlags>
</FileUpgradeFlags>
<OldToolsVersion>3.5</OldToolsVersion>
<UpgradeBackupLocation />
<TargetFrameworkProfile />
<PublishUrl>publish\</PublishUrl>
<Install>true</Install>
<InstallFrom>Disk</InstallFrom>
<UpdateEnabled>false</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateInterval>7</UpdateInterval>
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
<UpdatePeriodically>false</UpdatePeriodically>
<UpdateRequired>false</UpdateRequired>
<MapFileExtensions>true</MapFileExtensions>
<ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<IsWebBootstrapper>false</IsWebBootstrapper>
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<OutputPath>..\..\..\build\VS.Net.2010\Spring.Http.Tests\Debug\</OutputPath>
<AllowUnsafeBlocks>false</AllowUnsafeBlocks>
<BaseAddress>285212672</BaseAddress>
<CheckForOverflowUnderflow>false</CheckForOverflowUnderflow>
<ConfigurationOverrideFile>
</ConfigurationOverrideFile>
<DefineConstants>TRACE;DEBUG;NET_2_0;NET_3_0;NET_3_5;NET_4_0</DefineConstants>
<DocumentationFile>
</DocumentationFile>
<DebugSymbols>true</DebugSymbols>
<FileAlignment>4096</FileAlignment>
<NoStdLib>false</NoStdLib>
<NoWarn>
</NoWarn>
<Optimize>false</Optimize>
<RegisterForComInterop>false</RegisterForComInterop>
<RemoveIntegerChecks>false</RemoveIntegerChecks>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<WarningLevel>4</WarningLevel>
<DebugType>full</DebugType>
<ErrorReport>prompt</ErrorReport>
<UseVSHostingProcess>true</UseVSHostingProcess>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<OutputPath>..\..\..\build\VS.Net.2010\Spring.Http.Tests\Release\</OutputPath>
<AllowUnsafeBlocks>false</AllowUnsafeBlocks>
<BaseAddress>285212672</BaseAddress>
<CheckForOverflowUnderflow>false</CheckForOverflowUnderflow>
<ConfigurationOverrideFile>
</ConfigurationOverrideFile>
<DefineConstants>TRACE;NET_2_0;NET_3_0;NET_3_5;NET_4_0</DefineConstants>
<DocumentationFile>
</DocumentationFile>
<DebugSymbols>false</DebugSymbols>
<FileAlignment>4096</FileAlignment>
<NoStdLib>false</NoStdLib>
<NoWarn>
</NoWarn>
<Optimize>true</Optimize>
<RegisterForComInterop>false</RegisterForComInterop>
<RemoveIntegerChecks>false</RemoveIntegerChecks>
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
<WarningLevel>4</WarningLevel>
<DebugType>none</DebugType>
<ErrorReport>prompt</ErrorReport>
</PropertyGroup>
<ItemGroup>
<Reference Include="Common.Logging, Version=1.2.0.0, Culture=neutral, PublicKeyToken=af08829b84f0328e">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\lib\Net\2.0\Common.Logging.dll</HintPath>
</Reference>
<Reference Include="nunit.framework">
<Name>nunit.framework</Name>
<HintPath>..\..\..\lib\Net\2.0\nunit.framework.dll</HintPath>
</Reference>
<Reference Include="Rhino.Mocks, Version=3.4.0.0, Culture=neutral, PublicKeyToken=0b3305902db7183f, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\lib\Net\2.0\Rhino.Mocks.dll</HintPath>
</Reference>
<Reference Include="System">
<Name>System</Name>
</Reference>
<Reference Include="System.Core" />
<Reference Include="System.IdentityModel" />
<Reference Include="System.Runtime.Serialization" />
<Reference Include="System.ServiceModel" />
<Reference Include="System.ServiceModel.Web" />
<Reference Include="System.XML" />
<Reference Include="System.Xml.Linq" />
</ItemGroup>
<ItemGroup>
<Compile Include="AssemblyInfo.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="Http\Client\AbstractClientHttpRequestFactoryIntegrationTests.cs" />
<Compile Include="Http\Client\WebClientHttpRequestFactoryIntegrationTests.cs" />
<Compile Include="Http\Converters\ByteArrayHttpMessageConverterTests.cs" />
<Compile Include="Http\Converters\Feed\Atom10FeedHttpMessageConverterTests.cs" />
<Compile Include="Http\Converters\Feed\FeedHttpMessageConverterIntegrationTests.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="Http\Converters\Feed\Rss20FeedHttpMessageConverterTests.cs" />
<Compile Include="Http\Converters\FileInfoHttpMessageConverterTests.cs" />
<Compile Include="Http\Converters\FormHttpMessageConverterTests.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="Http\Converters\Json\JsonHttpMessageConverterTests.cs" />
<Compile Include="Http\Converters\Json\JsonHttpMessageConverterIntegrationTests.cs" />
<Compile Include="Http\Converters\StringHttpMessageConverterTests.cs" />
<Compile Include="Http\Converters\Xml\XmlHttpMessageConverterIntegrationTests.cs" />
<Compile Include="Http\Converters\Xml\XElementHttpMessageConverterTests.cs" />
<Compile Include="Http\Converters\Xml\XmlSerializableHttpMessageConverterTests.cs" />
<Compile Include="Http\Converters\Xml\DataContractHttpMessageConverterTests.cs" />
<Compile Include="Http\Converters\Xml\XmlDocumentHttpMessageConverterTests.cs" />
<Compile Include="Http\HttpHeadersTests.cs" />
<Compile Include="Http\MediaTypeTests.cs" />
<Compile Include="Http\MockHttpInputMessage.cs" />
<Compile Include="Http\MockHttpOuputMessage.cs" />
<Compile Include="Http\Rest\HttpStatusCodeExceptionTests.cs" />
<Compile Include="Http\Rest\RestTemplateIntegrationTests.cs" />
<Compile Include="Http\Rest\RestTemplateTests.cs" />
<Compile Include="Util\SerializationTestUtils.cs" />
<Compile Include="Util\UriTemplateTests.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\src\Spring\Spring.Http\Spring.Http.2010.csproj">
<Project>{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</Project>
<Name>Spring.Http.2010</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<None Include="Spring.Http.Tests.dll.config" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<PropertyGroup>
<PreBuildEvent>
</PreBuildEvent>
<PostBuildEvent>echo "Copying .xml files for tests"
xcopy "$(ProjectDir)Data" ..\..\..\..\build\VS.Net.2010\Spring.Http.Tests\$(ConfigurationName)\ /y /s /q /d
xcopy "$(ProjectDir)$(TargetFileName).config" ..\..\..\..\build\VS.Net.2010\Spring.Http.Tests\$(ConfigurationName)\ /y /s /q</PostBuildEvent>
</PropertyGroup>
</Project>

View File

@@ -1,18 +0,0 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="common">
<section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging" />
</sectionGroup>
</configSections>
<common>
<logging>
<factoryAdapter type="Common.Logging.Simple.TraceLoggerFactoryAdapter, Common.Logging">
<arg key="level" value="ALL" />
</factoryAdapter>
</logging>
</common>
</configuration>

View File

@@ -1,80 +0,0 @@
#region License
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace Spring.Util
{
/// <summary>
/// Utilities for testing serializability of objects.
/// </summary>
/// <remarks>
/// Exposes static methods for use in other test cases.
/// </remarks>
/// <author>Rod Johnson</author>
/// <author>Simon White (.NET)</author>
public sealed class SerializationTestUtils
{
/// <summary>
/// Attempts to serialize the specified object to an in-memory stream.
/// </summary>
/// <param name="o">the object to serialize</param>
public static void TryBinarySerialization(object o)
{
using (Stream stream = new MemoryStream())
{
BinaryFormatter bformatter = new BinaryFormatter();
bformatter.Serialize(stream, o);
}
}
/// <summary>
/// Tests whether the specified object is serializable.
/// </summary>
/// <param name="o">the object to test.</param>
/// <returns>true if the object is serializable, otherwise false.</returns>
public static bool IsBinarySerializable(object o)
{
return o == null ? true : o.GetType().IsSerializable;
}
/// <summary>
/// Serializes the specified object to an in-memory stream, and returns
/// the result of deserializing the object stream.
/// </summary>
/// <param name="o">the object to use.</param>
/// <returns>the deserialized object.</returns>
public static object BinarySerializeAndDeserialize(object o)
{
using (Stream stream = new MemoryStream())
{
BinaryFormatter bformatter = new BinaryFormatter();
bformatter.Serialize(stream, o);
stream.Flush();
stream.Seek(0, SeekOrigin.Begin);
object o2 = bformatter.Deserialize(stream);
return o2;
}
}
}
}

View File

@@ -1,227 +0,0 @@
#region License
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System;
using System.Collections.Generic;
using NUnit.Framework;
namespace Spring.Util
{
/// <summary>
/// Unit tests for the UriTemplate class.
/// </summary>
/// <author>Arjen Poutsma</author>
/// <author>Juergen Hoeller</author>
/// <author>Bruno Baia (.NET)</author>
[TestFixture]
public class UriTemplateTests
{
[Test]
public void GetVariableNames()
{
UriTemplate template = new UriTemplate("http://example.com/hotels/{hotel}/bookings/{booking}");
string[] variableNames = template.VariableNames;
Assert.AreEqual(new string[] { "hotel", "booking" }, variableNames, "Invalid variable names");
}
[Test]
public void ExpandVarArgs()
{
// absolute
UriTemplate template = new UriTemplate("http://example.com/hotels/{hotel}/bookings/{booking}");
Uri result = template.Expand("1", "42");
Assert.AreEqual(new Uri("http://example.com/hotels/1/bookings/42"), result, "Invalid expanded template");
// relative
template = new UriTemplate("/hotels/{hotel}/bookings/{booking}");
result = template.Expand("1", "42");
Assert.AreEqual(new Uri("/hotels/1/bookings/42", UriKind.Relative), result, "Invalid expanded template");
}
[Test]
public void MultipleExpandVarArgs()
{
UriTemplate template = new UriTemplate("http://example.com/hotels/{hotel}/bookings/{booking}");
Uri result = template.Expand("2", 21);
result = template.Expand(1, "42");
Assert.AreEqual(new Uri("http://example.com/hotels/1/bookings/42"), result, "Invalid expanded template");
}
[Test]
[ExpectedException(
typeof(ArgumentException),
ExpectedMessage = "Invalid amount of variables values in 'http://example.com/hotels/{hotel}/bookings/{booking}': expected 2; got 3")]
public void ExpandVarArgsInvalidAmountVariables()
{
UriTemplate template = new UriTemplate("http://example.com/hotels/{hotel}/bookings/{booking}");
template.Expand("1", "42", 100);
}
[Test]
public void ExpandVarArgsDuplicateVariables()
{
UriTemplate template = new UriTemplate("http://example.com/order/{c}/{c}/{c}");
Assert.AreEqual(new string[] { "c" }, template.VariableNames, "Invalid variable names");
Uri result = template.Expand("cheeseburger");
Assert.AreEqual(new Uri("http://example.com/order/cheeseburger/cheeseburger/cheeseburger"), result, "Invalid expanded template");
}
[Test]
public void ExpandDictionary()
{
IDictionary<string, object> uriVariables = new Dictionary<string, object>(2);
uriVariables.Add("booking", "42");
uriVariables.Add("hotel", 1);
// absolute
UriTemplate template = new UriTemplate("http://example.com/hotels/{hotel}/bookings/{booking}");
Uri result = template.Expand(uriVariables);
Assert.AreEqual(new Uri("http://example.com/hotels/1/bookings/42"), result, "Invalid expanded template");
// relative
template = new UriTemplate("hotels/{hotel}/bookings/{booking}");
result = template.Expand(uriVariables);
Assert.AreEqual(new Uri("hotels/1/bookings/42", UriKind.Relative), result, "Invalid expanded template");
}
[Test]
public void MultipleExpandDictionary()
{
UriTemplate template = new UriTemplate("http://example.com/hotels/{hotel}/bookings/{booking}");
IDictionary<string, object> uriVariables = new Dictionary<string, object>(2);
uriVariables.Add("booking", 21);
uriVariables.Add("hotel", "2");
Uri result = template.Expand(uriVariables);
uriVariables = new Dictionary<string, object>(2);
uriVariables.Add("booking", "42");
uriVariables.Add("hotel", "1");
result = template.Expand(uriVariables);
Assert.AreEqual(new Uri("http://example.com/hotels/1/bookings/42"), result, "Invalid expanded template");
}
[Test]
[ExpectedException(
typeof(ArgumentException),
ExpectedMessage = "Invalid amount of variables values in 'http://example.com/hotels/{hotel}/bookings/{booking}': expected 2; got 1")]
public void ExpandDictionaryInvalidAmountVariables()
{
IDictionary<string, object> uriVariables = new Dictionary<string, object>(2);
uriVariables.Add("hotel", 1);
UriTemplate template = new UriTemplate("http://example.com/hotels/{hotel}/bookings/{booking}");
template.Expand(uriVariables);
}
[Test]
[ExpectedException(
typeof(ArgumentException),
ExpectedMessage = "'uriVariables' dictionary has no value for 'hotel'")]
public void ExpandDictionaryUnboundVariables()
{
IDictionary<string, object> uriVariables = new Dictionary<string, object>(2);
uriVariables.Add("booking", "42");
uriVariables.Add("bar", 1);
UriTemplate template = new UriTemplate("http://example.com/hotels/{hotel}/bookings/{booking}");
template.Expand(uriVariables);
}
[Test]
public void ExpandEncoded()
{
UriTemplate template = new UriTemplate("http://example.com/hotel list/{hotel}");
Uri result = template.Expand("Z\u00fcrich");
Assert.AreEqual(new Uri("http://example.com/hotel%20list/Z%C3%BCrich"), result, "Invalid expanded template");
}
[Test]
public void Matches()
{
UriTemplate template = new UriTemplate("http://example.com/hotels/{hotel}/bookings/{booking}/");
Assert.IsTrue(template.Matches("http://example.com/hotels/1/bookings/42/"), "UriTemplate does not match");
Assert.IsFalse(template.Matches("hhhhttp://example.com/hotels/1/bookings/42/"), "UriTemplate matches");
Assert.IsFalse(template.Matches("http://example.com/hotels/1/bookings/42/blabla"), "UriTemplate matches");
Assert.IsFalse(template.Matches("http://example.com/hotels/bookings/"), "UriTemplate matches");
Assert.IsFalse(template.Matches(""), "UriTemplate matches");
Assert.IsFalse(template.Matches(null), "UriTemplate matches");
}
[Test]
public void Match()
{
UriTemplate template = new UriTemplate("http://example.com/hotels/{hotel}/bookings/{booking}");
IDictionary<string, string> result = template.Match("http://example.com/hotels/1/bookings/42");
Assert.AreEqual(2, result.Count);
Assert.AreEqual("1", result["hotel"]);
Assert.AreEqual("42", result["booking"]);
result = template.Match("http://example.com/hotels/1/bookings");
Assert.AreEqual(0, result.Count);
}
[Test]
public void matchDuplicate()
{
UriTemplate template = new UriTemplate("/order/{c}/{c}/{c}");
IDictionary<string, string> result = template.Match("/order/cheeseburger/cheeseburger/cheeseburger");
Assert.AreEqual(1, result.Count);
Assert.AreEqual("cheeseburger", result["c"]);
}
[Test]
public void MatchMultipleInOneSegment()
{
UriTemplate template = new UriTemplate("/{foo}-{bar}");
IDictionary<string, string> result = template.Match("/12-34");
Assert.AreEqual(2, result.Count);
Assert.AreEqual("12", result["foo"]);
Assert.AreEqual("34", result["bar"]);
}
[Test]
public void MatchesQueryVariables()
{
UriTemplate template = new UriTemplate("/search?q={query}");
Assert.IsTrue(template.Matches("/search?q=foo"));
}
[Test]
public void MatchesFragments()
{
UriTemplate template = new UriTemplate("/search#{fragment}");
Assert.IsTrue(template.Matches("/search#foo"));
template = new UriTemplate("/search?query={query}#{fragment}");
Assert.IsTrue(template.Matches("/search?query=foo#bar"));
}
[Test]
public void ExpandWithAtSign()
{
UriTemplate template = new UriTemplate("http://localhost/query={query}");
Uri uri = template.Expand("foo@bar");
Assert.AreEqual("http://localhost/query=foo@bar", uri.ToString());
}
}
}