REST client API: Added tests for the Spring.Http.Client namespace (SPRNET-1345)
This commit is contained in:
@@ -114,7 +114,7 @@ namespace Spring.Http.Client
|
||||
public IClientHttpResponse Execute()
|
||||
{
|
||||
this.EnsureNotExecuted();
|
||||
|
||||
|
||||
try
|
||||
{
|
||||
// Prepare
|
||||
@@ -138,17 +138,20 @@ namespace Spring.Http.Client
|
||||
}
|
||||
catch (WebException ex)
|
||||
{
|
||||
// This exception will be raised if the server didn't return 200 - OK
|
||||
// Try to retrieve more information about the network error
|
||||
// This exception can be raised with some status code
|
||||
// Try to retrieve the response from the error
|
||||
HttpWebResponse httpWebResponse = ex.Response as HttpWebResponse;
|
||||
if (httpWebResponse != null)
|
||||
{
|
||||
this.isExecuted = true;
|
||||
return this.CreateClientHttpResponse(httpWebResponse);
|
||||
}
|
||||
throw;
|
||||
}
|
||||
this.isExecuted = true;
|
||||
finally
|
||||
{
|
||||
this.isExecuted = true;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
#endif
|
||||
@@ -273,8 +276,8 @@ namespace Spring.Http.Client
|
||||
throw;
|
||||
}
|
||||
exception = ex;
|
||||
// This exception will be raised if the server didn't return 200 - OK
|
||||
// Try to retrieve more information about the network error
|
||||
// This exception can be raised with some status code
|
||||
// Try to retrieve the response from the error
|
||||
if (ex is WebException)
|
||||
{
|
||||
HttpWebResponse httpWebResponse = ((WebException)ex).Response as HttpWebResponse;
|
||||
|
||||
@@ -28,6 +28,7 @@ namespace Spring.Http.Client
|
||||
/// <see cref="IClientHttpRequestFactory"/> implementation that uses
|
||||
/// .NET <see cref="HttpWebRequest"/>'s class to create requests.
|
||||
/// </summary>
|
||||
/// <see cref="WebClientHttpRequest"/>
|
||||
/// <author>Bruno Baia</author>
|
||||
public class WebClientHttpRequestFactory : IClientHttpRequestFactory
|
||||
{
|
||||
@@ -87,8 +88,7 @@ namespace Spring.Http.Client
|
||||
|
||||
private int? _timeout;
|
||||
/// <summary>
|
||||
/// Gets or sets the time-out value in milliseconds for the <see cref="M:System.Net.HttpWebRequest.GetResponse()"/>
|
||||
/// and <see cref="M:System.Net.HttpWebRequest.GetRequestStream()"/> methods.
|
||||
/// Gets or sets the time-out value in milliseconds for synchrone request only.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The default is 100,000 milliseconds (100 seconds).
|
||||
|
||||
@@ -29,6 +29,14 @@ namespace Spring.Http
|
||||
/// <author>Bruno Baia</author>
|
||||
public class HttpEntity : HttpEntity<object>
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new, empty instance of <see cref="HttpEntity"/> with no body or headers.
|
||||
/// </summary>
|
||||
public HttpEntity()
|
||||
: base()
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of <see cref="HttpEntity"/> with the given body.
|
||||
/// </summary>
|
||||
|
||||
@@ -20,6 +20,8 @@
|
||||
|
||||
using System.Net;
|
||||
|
||||
using Spring.Util;
|
||||
|
||||
namespace Spring.Http
|
||||
{
|
||||
/// <summary>
|
||||
@@ -59,6 +61,14 @@ namespace Spring.Http
|
||||
get { return (this.body != null); }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new, empty instance of <see cref="HttpEntity{T}"/> with no body or headers.
|
||||
/// </summary>
|
||||
public HttpEntity()
|
||||
: this(null, new HttpHeaders())
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of <see cref="HttpEntity{T}"/> with the given body.
|
||||
/// </summary>
|
||||
@@ -84,6 +94,8 @@ namespace Spring.Http
|
||||
/// <param name="headers">The entity headers.</param>
|
||||
public HttpEntity(T body, HttpHeaders headers)
|
||||
{
|
||||
AssertUtils.ArgumentNotNull(headers, "headers");
|
||||
|
||||
this.body = body;
|
||||
this.headers = headers;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,440 @@
|
||||
#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
|
||||
@@ -0,0 +1,182 @@
|
||||
#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
|
||||
@@ -61,7 +61,7 @@ namespace Spring.Http.Converters.Feed
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDownClass()
|
||||
public void TearDown()
|
||||
{
|
||||
webServiceHost.Close();
|
||||
}
|
||||
|
||||
@@ -64,7 +64,7 @@ namespace Spring.Http.Converters.Json
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDownClass()
|
||||
public void TearDown()
|
||||
{
|
||||
webServiceHost.Close();
|
||||
}
|
||||
|
||||
@@ -62,7 +62,7 @@ namespace Spring.Http.Converters.Xml
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDownClass()
|
||||
public void TearDown()
|
||||
{
|
||||
webServiceHost.Close();
|
||||
}
|
||||
|
||||
@@ -62,7 +62,7 @@ namespace Spring.Http.Rest
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDownClass()
|
||||
public void TearDown()
|
||||
{
|
||||
webServiceHost.Close();
|
||||
}
|
||||
@@ -249,26 +249,6 @@ namespace Spring.Http.Rest
|
||||
Assert.AreEqual("User id '3' created with 'Maryse Baia'", result.StatusDescription, "Invalid status description");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ExchangeWithSpecialHeaders() // releated to HttpWebRequest implementation
|
||||
{
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
// Accept & Content-Type automatically set by RestTemplate
|
||||
headers["Connection"] = "close";
|
||||
headers.ContentLength = 10;
|
||||
headers.Date = DateTime.Now;
|
||||
headers["Expect"] = "bla";
|
||||
headers.IfModifiedSince = DateTime.Now;
|
||||
headers["Referer"] = "http://www.springframework.net/";
|
||||
//headers["Transfer-Encoding"] = "Identity";
|
||||
headers["User-Agent"] = "Unit tests";
|
||||
HttpEntity entity = new HttpEntity("Bruno Baia", headers);
|
||||
|
||||
HttpResponseMessage<string> result = template.Exchange<string>(
|
||||
"user", HttpMethod.POST, entity);
|
||||
}
|
||||
|
||||
|
||||
[Test]
|
||||
[ExpectedException(typeof(HttpClientErrorException),
|
||||
ExpectedMessage = "The server returned 'Not Found' with the status code 404 - NotFound.")]
|
||||
|
||||
@@ -121,28 +121,20 @@ namespace Spring.Http.Rest
|
||||
template.Execute<object>("hotels/{hotel}/bookings/{booking}", HttpMethod.GET, null, null, "42", "21");
|
||||
}
|
||||
|
||||
//[Test]
|
||||
//public void errorHandling() {
|
||||
// Expect.Call(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.GET)).andReturn(request);
|
||||
// Expect.Call(request.execute()).andReturn(response);
|
||||
// Expect.Call(errorHandler.hasError(response)).andReturn(true);
|
||||
// Expect.Call(response.getStatusCode()).andReturn(HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
// Expect.Call(response.getStatusText()).andReturn("Internal Server Error");
|
||||
// errorHandler.handleError(response);
|
||||
// expectLastCall().andThrow(new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR));
|
||||
// response.close();
|
||||
[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();
|
||||
mocks.ReplayAll();
|
||||
|
||||
// try {
|
||||
// template.execute("http://example.com", HttpMethod.GET, null, null);
|
||||
// fail("HttpServerErrorException expected");
|
||||
// }
|
||||
// catch (HttpServerErrorException ex) {
|
||||
// // expected
|
||||
// }
|
||||
// mocks.ReplayAll();
|
||||
//}
|
||||
template.Execute<object>("http://example.com", HttpMethod.GET, null, null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetForObject()
|
||||
|
||||
@@ -90,6 +90,8 @@
|
||||
</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" />
|
||||
|
||||
@@ -90,6 +90,9 @@
|
||||
<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>
|
||||
@@ -106,6 +109,8 @@
|
||||
</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" />
|
||||
|
||||
@@ -109,6 +109,7 @@
|
||||
<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" />
|
||||
@@ -119,6 +120,8 @@
|
||||
<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">
|
||||
|
||||
Reference in New Issue
Block a user