REST client API: Silverlight and Windows Phone support (SPRNET-1345)

This commit is contained in:
bbaia
2010-12-30 23:07:54 +00:00
parent e9de2313a5
commit 57a25d344b
154 changed files with 27801 additions and 1789 deletions

View File

@@ -1,7 +1,7 @@
#region License
/*
* Copyright 2002-2010 the original author or authors.
* 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.

View File

@@ -1,7 +1,7 @@
#region License
/*
* Copyright 2002-2010 the original author or authors.
* 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.
@@ -67,13 +67,15 @@ namespace Spring.Http.Converters
{
byte[] body = new byte[] { 0x1, 0x2 };
HttpWebResponse webResponse = mocks.CreateMock<HttpWebResponse>();
Expect.Call<Stream>(webResponse.GetResponseStream()).Return(new MemoryStream(body));
Expect.Call<long>(webResponse.ContentLength).Return(2);
IHttpInputMessage message = mocks.CreateMock<IHttpInputMessage>();
Expect.Call<Stream>(message.Body).Return(new MemoryStream(body));
HttpHeaders headers = new HttpHeaders();
headers.ContentLength = body.Length;
Expect.Call<HttpHeaders>(message.Headers).Return(headers).Repeat.Any();
mocks.ReplayAll();
byte[] result = converter.Read<byte[]>(webResponse);
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");
@@ -88,17 +90,20 @@ namespace Spring.Http.Converters
byte[] body = new byte[] { 0x1, 0x2 };
HttpWebRequest webRequest = mocks.CreateMock<HttpWebRequest>();
Expect.Call(webRequest.ContentType = "application/octet-stream").PropertyBehavior();
Expect.Call(webRequest.ContentLength = 2).PropertyBehavior();
Expect.Call<Stream>(webRequest.GetRequestStream()).Return(requestStream);
IHttpOutputMessage message = mocks.CreateMock<IHttpOutputMessage>();
Expect.Call(message.Body).PropertyBehavior();
HttpHeaders headers = new HttpHeaders();
Expect.Call<HttpHeaders>(message.Headers).Return(headers).Repeat.Any();
mocks.ReplayAll();
converter.Write(body, null, webRequest);
converter.Write(body, null, message);
message.Body(requestStream);
byte[] result = requestStream.ToArray();
Assert.AreEqual(body, result, "Invalid result");
Assert.AreEqual(new MediaType("application", "octet-stream"), message.Headers.ContentType, "Invalid content-type");
//Assert.AreEqual(2, message.Headers.ContentLength, "Invalid content-length");
mocks.VerifyAll();
}

View File

@@ -2,7 +2,7 @@
#region License
/*
* Copyright 2002-2010 the original author or authors.
* 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.
@@ -77,12 +77,12 @@ namespace Spring.Http.Converters.Feed
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));
HttpWebResponse webResponse = mocks.CreateMock<HttpWebResponse>();
Expect.Call<Stream>(webResponse.GetResponseStream()).Return(new MemoryStream(Encoding.UTF8.GetBytes(body)));
IHttpInputMessage message = mocks.CreateMock<IHttpInputMessage>();
Expect.Call<Stream>(message.Body).Return(new MemoryStream(Encoding.UTF8.GetBytes(body)));
mocks.ReplayAll();
SyndicationFeed result = converter.Read<SyndicationFeed>(webResponse);
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");
@@ -113,17 +113,20 @@ namespace Spring.Http.Converters.Feed
body.Authors.Add(sp);
body.Copyright = new TextSyndicationContent("Copyright 2010");
HttpWebRequest webRequest = mocks.CreateMock<HttpWebRequest>();
Expect.Call(webRequest.ContentType = "application/atom+xml").PropertyBehavior();
Expect.Call(webRequest.ContentLength = 1337).PropertyBehavior();
Expect.Call<Stream>(webRequest.GetRequestStream()).Return(requestStream);
IHttpOutputMessage message = mocks.CreateMock<IHttpOutputMessage>();
Expect.Call(message.Body).PropertyBehavior();
HttpHeaders headers = new HttpHeaders();
Expect.Call<HttpHeaders>(message.Headers).Return(headers).Repeat.Any();
mocks.ReplayAll();
converter.Write(body, null, webRequest);
converter.Write(body, null, message);
message.Body(requestStream);
byte[] result = requestStream.ToArray();
Assert.AreEqual(expectedBody, Encoding.UTF8.GetString(result), "Invalid result");
Assert.AreEqual(new MediaType("application", "atom+xml"), message.Headers.ContentType, "Invalid content-type");
//Assert.IsTrue(message.Headers.ContentLength > -1, "Invalid content-length");
mocks.VerifyAll();
}

View File

@@ -2,7 +2,7 @@
#region License
/*
* Copyright 2002-2010 the original author or authors.
* 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.

View File

@@ -2,7 +2,7 @@
#region License
/*
* Copyright 2002-2010 the original author or authors.
* 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.
@@ -78,12 +78,12 @@ namespace Spring.Http.Converters.Feed
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));
HttpWebResponse webResponse = mocks.CreateMock<HttpWebResponse>();
Expect.Call<Stream>(webResponse.GetResponseStream()).Return(new MemoryStream(Encoding.UTF8.GetBytes(body)));
IHttpInputMessage message = mocks.CreateMock<IHttpInputMessage>();
Expect.Call<Stream>(message.Body).Return(new MemoryStream(Encoding.UTF8.GetBytes(body)));
mocks.ReplayAll();
SyndicationFeed result = converter.Read<SyndicationFeed>(webResponse);
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");
@@ -112,17 +112,20 @@ namespace Spring.Http.Converters.Feed
body.Authors.Add(sp);
body.Copyright = new TextSyndicationContent("Copyright 2010");
HttpWebRequest webRequest = mocks.CreateMock<HttpWebRequest>();
Expect.Call(webRequest.ContentType = "application/rss+xml").PropertyBehavior();
Expect.Call(webRequest.ContentLength = 1337).PropertyBehavior();
Expect.Call<Stream>(webRequest.GetRequestStream()).Return(requestStream);
IHttpOutputMessage message = mocks.CreateMock<IHttpOutputMessage>();
Expect.Call(message.Body).PropertyBehavior();
HttpHeaders headers = new HttpHeaders();
Expect.Call<HttpHeaders>(message.Headers).Return(headers).Repeat.Any();
mocks.ReplayAll();
converter.Write(body, null, webRequest);
converter.Write(body, null, message);
message.Body(requestStream);
byte[] result = requestStream.ToArray();
Assert.AreEqual(expectedBody, Encoding.UTF8.GetString(result), "Invalid result");
Assert.AreEqual(new MediaType("application", "rss+xml"), message.Headers.ContentType, "Invalid content-type");
//Assert.IsTrue(message.Headers.ContentLength > -1, "Invalid content-length");
mocks.VerifyAll();
}

View File

@@ -0,0 +1,172 @@
#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.Collections.Generic;
using System.Collections.Specialized;
using NUnit.Framework;
using Rhino.Mocks;
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;
private MockRepository mocks;
[SetUp]
public void SetUp()
{
mocks = new MockRepository();
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);
IHttpInputMessage message = mocks.CreateMock<IHttpInputMessage>();
Expect.Call<Stream>(message.Body).Return(new MemoryStream(Encoding.UTF8.GetBytes(body)));
HttpHeaders headers = new HttpHeaders();
headers.ContentType = mediaType;
Expect.Call<HttpHeaders>(message.Headers).Return(headers).Repeat.Any();
mocks.ReplayAll();
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");
mocks.VerifyAll();
}
[Test]
public void WriteForm()
{
MemoryStream requestStream = new MemoryStream();
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);
IHttpOutputMessage message = mocks.CreateMock<IHttpOutputMessage>();
Expect.Call(message.Body).PropertyBehavior();
HttpHeaders headers = new HttpHeaders();
Expect.Call<HttpHeaders>(message.Headers).Return(headers).Repeat.Any();
mocks.ReplayAll();
converter.Write(body, MediaType.APPLICATION_FORM_URLENCODED, message);
message.Body(requestStream);
byte[] result = requestStream.ToArray();
Assert.AreEqual(expectedBody, charSetEncoding.GetString(result), "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");
mocks.VerifyAll();
}
[Test]
[Ignore] //TODO: relative path
public void WriteMultipart()
{
MemoryStream requestStream = new MemoryStream();
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"));
IHttpOutputMessage message = mocks.CreateMock<IHttpOutputMessage>();
Expect.Call(message.Body).PropertyBehavior();
HttpHeaders headers = new HttpHeaders();
Expect.Call<HttpHeaders>(message.Headers).Return(headers).Repeat.Any();
mocks.ReplayAll();
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");
message.Body(requestStream);
byte[] result = requestStream.ToArray();
string resultAsString = Encoding.UTF8.GetString(result);
Assert.IsTrue(resultAsString.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(resultAsString.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(resultAsString.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(resultAsString.Contains("--" + boundary + "\r\nContent-Disposition: form-data; name=\"logo\"; filename=\"C:\\Users\\Bruno\\Pictures\\Hero\\downloadfile.jpeg\"\r\nContent-Type: application/octet-stream\r\n\r\n"), "Invalid content-disposition");
mocks.VerifyAll();
}
}
}

View File

@@ -2,7 +2,7 @@
#region License
/*
* Copyright 2002-2010 the original author or authors.
* 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.
@@ -89,7 +89,7 @@ namespace Spring.Http.Converters.Json
HttpResponseMessage result = template.PostForMessage("user", user);
Assert.IsNull(result.Body, "Invalid content");
Assert.AreEqual(new Uri(new Uri(uri), "/user/3"), new Uri(result.Headers[HttpResponseHeader.Location]), "Invalid location");
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");
}
@@ -146,7 +146,7 @@ namespace Spring.Http.Converters.Json
UriTemplateMatch match = context.IncomingRequest.UriTemplateMatch;
UriTemplate template = new UriTemplate("/user/{id}");
MediaType mediaType = MediaType.ParseMediaType(context.IncomingRequest.ContentType);
MediaType mediaType = MediaType.Parse(context.IncomingRequest.ContentType);
if (!String.IsNullOrEmpty(user.ID))
{

View File

@@ -2,7 +2,7 @@
#region License
/*
* Copyright 2002-2010 the original author or authors.
* 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.
@@ -64,12 +64,12 @@ namespace Spring.Http.Converters.Json
{
string body = "{\"ID\":\"1\",\"Name\":\"Bruno Baïa\"}";
HttpWebResponse webResponse = mocks.CreateMock<HttpWebResponse>();
Expect.Call<Stream>(webResponse.GetResponseStream()).Return(new MemoryStream(Encoding.UTF8.GetBytes(body)));
IHttpInputMessage message = mocks.CreateMock<IHttpInputMessage>();
Expect.Call<Stream>(message.Body).Return(new MemoryStream(Encoding.UTF8.GetBytes(body)));
mocks.ReplayAll();
CustomClass result = converter.Read<CustomClass>(webResponse);
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");
@@ -85,17 +85,20 @@ namespace Spring.Http.Converters.Json
string expectedBody = "{\"ID\":\"1\",\"Name\":\"Bruno Baïa\"}";
CustomClass body = new CustomClass("1", "Bruno Baïa");
HttpWebRequest webRequest = mocks.CreateMock<HttpWebRequest>();
Expect.Call(webRequest.ContentType = "application/json").PropertyBehavior();
Expect.Call(webRequest.ContentLength = 1337).PropertyBehavior();
Expect.Call<Stream>(webRequest.GetRequestStream()).Return(requestStream);
IHttpOutputMessage message = mocks.CreateMock<IHttpOutputMessage>();
Expect.Call(message.Body).PropertyBehavior();
HttpHeaders headers = new HttpHeaders();
Expect.Call<HttpHeaders>(message.Headers).Return(headers).Repeat.Any();
mocks.ReplayAll();
converter.Write(body, null, webRequest);
converter.Write(body, null, message);
message.Body(requestStream);
byte[] result = requestStream.ToArray();
Assert.AreEqual(expectedBody, Encoding.UTF8.GetString(result), "Invalid result");
Assert.AreEqual(new MediaType("application", "json"), message.Headers.ContentType, "Invalid content-type");
//Assert.IsTrue(message.Headers.ContentLength > -1, "Invalid content-length");
mocks.VerifyAll();
}

View File

@@ -1,7 +1,7 @@
#region License
/*
* Copyright 2002-2010 the original author or authors.
* 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.
@@ -18,6 +18,7 @@
#endregion
using System;
using System.IO;
using System.Net;
using System.Text;
@@ -71,13 +72,15 @@ namespace Spring.Http.Converters
Encoding charSetEncoding = Encoding.GetEncoding(charSet);
MediaType mediaType = new MediaType("text", "plain", charSet);
HttpWebResponse webResponse = mocks.CreateMock<HttpWebResponse>();
Expect.Call<Stream>(webResponse.GetResponseStream()).Return(new MemoryStream(Encoding.UTF8.GetBytes(body)));
Expect.Call<string>(webResponse.ContentType).Return(mediaType.ToString());
IHttpInputMessage message = mocks.CreateMock<IHttpInputMessage>();
Expect.Call<Stream>(message.Body).Return(new MemoryStream(Encoding.UTF8.GetBytes(body)));
HttpHeaders headers = new HttpHeaders();
headers.ContentType = mediaType;
Expect.Call<HttpHeaders>(message.Headers).Return(headers).Repeat.Any();
mocks.ReplayAll();
string result = converter.Read<string>(webResponse);
string result = converter.Read<string>(message);
Assert.AreEqual(body, result, "Invalid result");
mocks.VerifyAll();
@@ -93,17 +96,20 @@ namespace Spring.Http.Converters
Encoding charSetEncoding = Encoding.GetEncoding(charSet);
MediaType mediaType = new MediaType("text", "plain", charSet);
HttpWebRequest webRequest = mocks.CreateMock<HttpWebRequest>();
Expect.Call(webRequest.ContentType = mediaType.ToString()).PropertyBehavior();
Expect.Call(webRequest.ContentLength = 1337).PropertyBehavior();
Expect.Call<Stream>(webRequest.GetRequestStream()).Return(requestStream);
IHttpOutputMessage message = mocks.CreateMock<IHttpOutputMessage>();
Expect.Call(message.Body).PropertyBehavior();
HttpHeaders headers = new HttpHeaders();
Expect.Call<HttpHeaders>(message.Headers).Return(headers).Repeat.Any();
mocks.ReplayAll();
converter.Write(body, null, webRequest);
converter.Write(body, null, message);
message.Body(requestStream);
byte[] result = requestStream.ToArray();
Assert.AreEqual(body, charSetEncoding.GetString(result), "Invalid result");
Assert.AreEqual(mediaType, message.Headers.ContentType, "Invalid content-type");
//Assert.AreEqual(charSetEncoding.GetBytes(body).Length, message.Headers.ContentLength, "Invalid content-length");
mocks.VerifyAll();
}
@@ -118,17 +124,20 @@ namespace Spring.Http.Converters
Encoding charSetEncoding = Encoding.GetEncoding(charSet);
MediaType mediaType = new MediaType("text", "plain", charSet);
HttpWebRequest webRequest = mocks.CreateMock<HttpWebRequest>();
Expect.Call(webRequest.ContentType = mediaType.ToString()).PropertyBehavior();
Expect.Call(webRequest.ContentLength = 1337).PropertyBehavior();
Expect.Call<Stream>(webRequest.GetRequestStream()).Return(requestStream);
IHttpOutputMessage message = mocks.CreateMock<IHttpOutputMessage>();
Expect.Call(message.Body).PropertyBehavior();
HttpHeaders headers = new HttpHeaders();
Expect.Call<HttpHeaders>(message.Headers).Return(headers).Repeat.Any();
mocks.ReplayAll();
converter.Write(body, mediaType, webRequest);
converter.Write(body, mediaType, message);
message.Body(requestStream);
byte[] result = requestStream.ToArray();
Assert.AreEqual(body, charSetEncoding.GetString(result), "Invalid result");
Assert.AreEqual(mediaType, message.Headers.ContentType, "Invalid content-type");
//Assert.AreEqual(charSetEncoding.GetBytes(body).Length, message.Headers.ContentLength, "Invalid content-length");
mocks.VerifyAll();
}

View File

@@ -1,122 +0,0 @@
#region License
/*
* Copyright 2002-2010 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.Collections.Specialized;
using NUnit.Framework;
using Rhino.Mocks;
namespace Spring.Http.Converters
{
/// <summary>
/// Unit tests for the UrlEncodedFormHttpMessageConverter class.
/// </summary>
/// <author>Arjen Poutsma</author>
/// <author>Bruno Baia (.NET)</author>
[TestFixture]
public class UrlEncodedFormHttpMessageConverterTests
{
private UrlEncodedFormHttpMessageConverter converter;
private MockRepository mocks;
[SetUp]
public void SetUp()
{
mocks = new MockRepository();
converter = new UrlEncodedFormHttpMessageConverter();
}
[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")));
}
[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")));
}
[Test]
public void Read()
{
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);
HttpWebResponse webResponse = mocks.CreateMock<HttpWebResponse>();
Expect.Call<Stream>(webResponse.GetResponseStream()).Return(new MemoryStream(Encoding.UTF8.GetBytes(body)));
Expect.Call<string>(webResponse.ContentType).Return(mediaType.ToString());
mocks.ReplayAll();
NameValueCollection result = converter.Read<NameValueCollection>(webResponse);
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");
mocks.VerifyAll();
}
[Test]
public void Write()
{
MemoryStream requestStream = new MemoryStream();
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);
MediaType mediaType = new MediaType("application", "x-www-form-urlencoded", charSet);
HttpWebRequest webRequest = mocks.CreateMock<HttpWebRequest>();
Expect.Call(webRequest.ContentType = mediaType.ToString()).PropertyBehavior();
Expect.Call(webRequest.ContentLength = 1337).PropertyBehavior();
Expect.Call<Stream>(webRequest.GetRequestStream()).Return(requestStream);
mocks.ReplayAll();
converter.Write(body, null, webRequest);
byte[] result = requestStream.ToArray();
Assert.AreEqual(expectedBody, charSetEncoding.GetString(result), "Invalid result");
mocks.VerifyAll();
}
}
}

View File

@@ -2,7 +2,7 @@
#region License
/*
* Copyright 2002-2010 the original author or authors.
* 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.
@@ -77,12 +77,12 @@ namespace Spring.Http.Converters.Xml
<ID>1</ID><Name>Bruno Baïa</Name>
</DataContractHttpMessageConverterTests.DataContractClass>";
HttpWebResponse webResponse = mocks.CreateMock<HttpWebResponse>();
Expect.Call<Stream>(webResponse.GetResponseStream()).Return(new MemoryStream(Encoding.UTF8.GetBytes(body)));
IHttpInputMessage message = mocks.CreateMock<IHttpInputMessage>();
Expect.Call<Stream>(message.Body).Return(new MemoryStream(Encoding.UTF8.GetBytes(body)));
mocks.ReplayAll();
DataContractClass result = converter.Read<DataContractClass>(webResponse);
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");
@@ -98,17 +98,20 @@ namespace Spring.Http.Converters.Xml
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");
HttpWebRequest webRequest = mocks.CreateMock<HttpWebRequest>();
Expect.Call(webRequest.ContentType = "application/xml").PropertyBehavior();
Expect.Call(webRequest.ContentLength = 1337).PropertyBehavior();
Expect.Call<Stream>(webRequest.GetRequestStream()).Return(requestStream);
IHttpOutputMessage message = mocks.CreateMock<IHttpOutputMessage>();
Expect.Call(message.Body).PropertyBehavior();
HttpHeaders headers = new HttpHeaders();
Expect.Call<HttpHeaders>(message.Headers).Return(headers).Repeat.Any();
mocks.ReplayAll();
converter.Write(body, null, webRequest);
converter.Write(body, null, message);
message.Body(requestStream);
byte[] result = requestStream.ToArray();
Assert.AreEqual(expectedBody, Encoding.UTF8.GetString(result), "Invalid result");
Assert.AreEqual(new MediaType("application", "xml"), message.Headers.ContentType, "Invalid content-type");
//Assert.IsTrue(message.Headers.ContentLength > -1, "Invalid content-length");
mocks.VerifyAll();
}

View File

@@ -2,7 +2,7 @@
#region License
/*
* Copyright 2002-2010 the original author or authors.
* 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.
@@ -73,12 +73,12 @@ namespace Spring.Http.Converters.Xml
{
string body = "<?xml version='1.0' encoding='UTF-8' ?><Root><TestElement testAttribute='value'/><TestElement testAttribute='novalue'/></Root>";
HttpWebResponse webResponse = mocks.CreateMock<HttpWebResponse>();
Expect.Call<Stream>(webResponse.GetResponseStream()).Return(new MemoryStream(Encoding.UTF8.GetBytes(body)));
IHttpInputMessage message = mocks.CreateMock<IHttpInputMessage>();
Expect.Call<Stream>(message.Body).Return(new MemoryStream(Encoding.UTF8.GetBytes(body)));
mocks.ReplayAll();
XElement result = converter.Read<XElement>(webResponse);
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")
@@ -101,17 +101,20 @@ namespace Spring.Http.Converters.Xml
new XElement("TestElement", 1),
new XElement("TestElement", 2));
HttpWebRequest webRequest = mocks.CreateMock<HttpWebRequest>();
Expect.Call(webRequest.ContentType = "application/xml").PropertyBehavior();
Expect.Call(webRequest.ContentLength = 1337).PropertyBehavior();
Expect.Call<Stream>(webRequest.GetRequestStream()).Return(requestStream);
IHttpOutputMessage message = mocks.CreateMock<IHttpOutputMessage>();
Expect.Call(message.Body).PropertyBehavior();
HttpHeaders headers = new HttpHeaders();
Expect.Call<HttpHeaders>(message.Headers).Return(headers).Repeat.Any();
mocks.ReplayAll();
converter.Write(body, null, webRequest);
converter.Write(body, null, message);
message.Body(requestStream);
byte[] result = requestStream.ToArray();
Assert.AreEqual(body.ToString(SaveOptions.DisableFormatting), Encoding.UTF8.GetString(result), "Invalid result");
Assert.AreEqual(new MediaType("application", "xml"), message.Headers.ContentType, "Invalid content-type");
//Assert.IsTrue(message.Headers.ContentLength > -1, "Invalid content-length");
mocks.VerifyAll();
}

View File

@@ -1,7 +1,7 @@
#region License
/*
* Copyright 2002-2010 the original author or authors.
* 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.
@@ -69,14 +69,14 @@ namespace Spring.Http.Converters.Xml
[Test]
public void Read()
{
string body = "<?xml version='1.0' encoding='UTF-8' ?><TestElement testAttribute='value' />";
string body = "<TestElement testAttribute='value' />";
HttpWebResponse webResponse = mocks.CreateMock<HttpWebResponse>();
Expect.Call<Stream>(webResponse.GetResponseStream()).Return(new MemoryStream(Encoding.UTF8.GetBytes(body)));
IHttpInputMessage message = mocks.CreateMock<IHttpInputMessage>();
Expect.Call<Stream>(message.Body).Return(new MemoryStream(Encoding.UTF8.GetBytes(body)));
mocks.ReplayAll();
XmlDocument result = converter.Read<XmlDocument>(webResponse);
XmlDocument result = converter.Read<XmlDocument>(message);
Assert.IsNotNull(result, "Invalid result");
XmlNode xmlNodeResult = result.SelectSingleNode("//TestElement");
Assert.IsNotNull(xmlNodeResult, "Invalid result");
@@ -93,19 +93,22 @@ namespace Spring.Http.Converters.Xml
MemoryStream requestStream = new MemoryStream();
XmlDocument body = new XmlDocument();
body.LoadXml("<?xml version='1.0' encoding='UTF-8' ?><TestElement testAttribute='value' />");
body.LoadXml("<TestElement testAttribute='value' />");
HttpWebRequest webRequest = mocks.CreateMock<HttpWebRequest>();
Expect.Call(webRequest.ContentType = "application/xml").PropertyBehavior();
Expect.Call(webRequest.ContentLength = 1337).PropertyBehavior();
Expect.Call<Stream>(webRequest.GetRequestStream()).Return(requestStream);
IHttpOutputMessage message = mocks.CreateMock<IHttpOutputMessage>();
Expect.Call(message.Body).PropertyBehavior();
HttpHeaders headers = new HttpHeaders();
Expect.Call<HttpHeaders>(message.Headers).Return(headers).Repeat.Any();
mocks.ReplayAll();
converter.Write(body, null, webRequest);
converter.Write(body, null, message);
message.Body(requestStream);
byte[] result = requestStream.ToArray();
Assert.AreEqual(body.OuterXml, Encoding.UTF8.GetString(result), "Invalid result");
Assert.AreEqual(new MediaType("application", "xml"), message.Headers.ContentType, "Invalid content-type");
//Assert.IsTrue(message.Headers.ContentLength > -1, "Invalid content-length");
mocks.VerifyAll();
}

View File

@@ -2,7 +2,7 @@
#region License
/*
* Copyright 2002-2010 the original author or authors.
* 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.
@@ -87,7 +87,7 @@ namespace Spring.Http.Converters.Xml
HttpResponseMessage result = template.PostForMessage("user/dc", user);
Assert.IsNull(result.Body, "Invalid content");
Assert.AreEqual(new Uri(new Uri(uri), "/user/dc/3"), new Uri(result.Headers[HttpResponseHeader.Location]), "Invalid location");
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");
}
@@ -113,7 +113,7 @@ namespace Spring.Http.Converters.Xml
HttpResponseMessage result = template.PostForMessage("user/xml", user);
Assert.IsNull(result.Body, "Invalid content");
Assert.AreEqual(new Uri(new Uri(uri), "/user/xml/3"), new Uri(result.Headers[HttpResponseHeader.Location]), "Invalid location");
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");
}
@@ -168,7 +168,7 @@ namespace Spring.Http.Converters.Xml
UriTemplateMatch match = context.IncomingRequest.UriTemplateMatch;
UriTemplate template = new UriTemplate("/user/dc/{id}");
MediaType mediaType = MediaType.ParseMediaType(context.IncomingRequest.ContentType);
MediaType mediaType = MediaType.Parse(context.IncomingRequest.ContentType);
if (!String.IsNullOrEmpty(user.ID))
{
@@ -213,7 +213,7 @@ namespace Spring.Http.Converters.Xml
UriTemplateMatch match = context.IncomingRequest.UriTemplateMatch;
UriTemplate template = new UriTemplate("/user/xml/{id}");
MediaType mediaType = MediaType.ParseMediaType(context.IncomingRequest.ContentType);
MediaType mediaType = MediaType.Parse(context.IncomingRequest.ContentType);
if (user.Element("ID") != null && !String.IsNullOrEmpty(user.Element("ID").Value))
{

View File

@@ -1,7 +1,7 @@
#region License
/*
* Copyright 2002-2010 the original author or authors.
* 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.
@@ -65,18 +65,17 @@ namespace Spring.Http.Converters.Xml
[Test]
public void Read()
{
string body = @"<?xml version='1.0' encoding='utf-8'?>
<CustomClass xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'>
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>";
HttpWebResponse webResponse = mocks.CreateMock<HttpWebResponse>();
Expect.Call<Stream>(webResponse.GetResponseStream()).Return(new MemoryStream(Encoding.UTF8.GetBytes(body)));
IHttpInputMessage message = mocks.CreateMock<IHttpInputMessage>();
Expect.Call<Stream>(message.Body).Return(new MemoryStream(Encoding.UTF8.GetBytes(body)));
mocks.ReplayAll();
CustomClass result = converter.Read<CustomClass>(webResponse);
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");
@@ -89,20 +88,23 @@ namespace Spring.Http.Converters.Xml
{
MemoryStream requestStream = new MemoryStream();
string expectedBody = "<?xml version=\"1.0\" encoding=\"utf-8\"?><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>";
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");
HttpWebRequest webRequest = mocks.CreateMock<HttpWebRequest>();
Expect.Call(webRequest.ContentType = "application/xml").PropertyBehavior();
Expect.Call(webRequest.ContentLength = 1337).PropertyBehavior();
Expect.Call<Stream>(webRequest.GetRequestStream()).Return(requestStream);
IHttpOutputMessage message = mocks.CreateMock<IHttpOutputMessage>();
Expect.Call(message.Body).PropertyBehavior();
HttpHeaders headers = new HttpHeaders();
Expect.Call<HttpHeaders>(message.Headers).Return(headers).Repeat.Any();
mocks.ReplayAll();
converter.Write(body, null, webRequest);
converter.Write(body, null, message);
message.Body(requestStream);
byte[] result = requestStream.ToArray();
Assert.AreEqual(expectedBody, Encoding.UTF8.GetString(result), "Invalid result");
Assert.AreEqual(new MediaType("application", "xml"), message.Headers.ContentType, "Invalid content-type");
//Assert.IsTrue(message.Headers.ContentLength > -1, "Invalid content-length");
mocks.VerifyAll();
}

View File

@@ -0,0 +1,336 @@
#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,7 +1,7 @@
#region License
/*
* Copyright 2002-2010 the original author or authors.
* 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.
@@ -112,10 +112,10 @@ namespace Spring.Http
}
[Test]
public void ParseMediaType()
public void Parse()
{
string s = "audio/*; q=0.2";
MediaType mediaType = MediaType.ParseMediaType(s);
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");
@@ -123,31 +123,31 @@ namespace Spring.Http
[Test]
[ExpectedException(typeof(ArgumentException))]
public void ParseMediaTypeNoSubtype()
public void ParseNoSubtype()
{
MediaType.ParseMediaType("audio");
MediaType.Parse("audio");
}
[Test]
[ExpectedException(typeof(ArgumentException))]
public void ParseMediaTypeNoSubtypeSlash()
public void ParseNoSubtypeSlash()
{
MediaType.ParseMediaType("audio/");
MediaType.Parse("audio/");
}
//[Test](expected = IllegalArgumentException.class)
//public void parseMediaTypeIllegalType() {
// MediaType.parseMediaType("audio(/basic");
//public void parseIllegalType() {
// MediaType.parse("audio(/basic");
//}
//[Test](expected = IllegalArgumentException.class)
//public void parseMediaTypeIllegalSubtype() {
// MediaType.parseMediaType("audio/basic)");
//public void parseIllegalSubtype() {
// MediaType.parse("audio/basic)");
//}
//[Test](expected = IllegalArgumentException.class)
//public void parseMediaTypeEmptyParameterAttribute() {
// MediaType.parseMediaType("audio/*;=value");
//public void parseEmptyParameterAttribute() {
// MediaType.parse("audio/*;=value");
//}
//[Test](expected = IllegalArgumentException.class)
@@ -156,39 +156,39 @@ namespace Spring.Http
//}
//[Test](expected = IllegalArgumentException.class)
//public void parseMediaTypeIllegalParameterAttribute() {
// MediaType.parseMediaType("audio/*;attr<=value");
//public void parseIllegalParameterAttribute() {
// MediaType.parse("audio/*;attr<=value");
//}
//[Test](expected = IllegalArgumentException.class)
//public void parseMediaTypeIllegalParameterValue() {
// MediaType.parseMediaType("audio/*;attr=v>alue");
//public void parseIllegalParameterValue() {
// MediaType.parse("audio/*;attr=v>alue");
//}
//[Test](expected = IllegalArgumentException.class)
//public void parseMediaTypeIllegalQualityFactor() {
// MediaType.parseMediaType("audio/basic;q=1.1");
//public void parseIllegalQualityFactor() {
// MediaType.parse("audio/basic;q=1.1");
//}
//[Test](expected = IllegalArgumentException.class)
//public void parseMediaTypeIllegalCharset() {
// MediaType.parseMediaType("text/html; charset=foo-bar");
//public void parseIllegalCharset() {
// MediaType.parse("text/html; charset=foo-bar");
//}
//[Test]
//public void parseMediaTypeQuotedParameterValue() {
// MediaType.parseMediaType("audio/*;attr=\"v>alue\"");
//public void parseQuotedParameterValue() {
// MediaType.parse("audio/*;attr=\"v>alue\"");
//}
//[Test](expected = IllegalArgumentException.class)
//public void parseMediaTypeIllegalQuotedParameterValue() {
// MediaType.parseMediaType("audio/*;attr=\"");
//public void parseIllegalQuotedParameterValue() {
// MediaType.parse("audio/*;attr=\"");
//}
//[Test]
//public void parseCharset() throws Exception {
// String s = "text/html; charset=iso-8859-1";
// MediaType mediaType = MediaType.parseMediaType(s);
// 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());
@@ -197,7 +197,7 @@ namespace Spring.Http
//[Test]
//public void parseQuotedCharset() {
// String s = "application/xml;charset=\"utf-8\"";
// MediaType mediaType = MediaType.parseMediaType(s);
// 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());
@@ -207,25 +207,12 @@ namespace Spring.Http
public void ParseURLConnectionMediaType()
{
string s = "*; q=.2";
MediaType mediaType = MediaType.ParseMediaType(s);
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 ParseMediaTypes()
{
string s = "text/plain; q=0.5, text/html, text/x-dvi; q=0.8, text/x-c";
List<MediaType> mediaTypes = MediaType.ParseMediaTypes(s);
Assert.NotNull(mediaTypes, "No media types returned");
Assert.AreEqual(4, mediaTypes.Count, "Invalid amount of media types");
mediaTypes = MediaType.ParseMediaTypes(null);
Assert.NotNull(mediaTypes, "No media types returned");
Assert.AreEqual(0, mediaTypes.Count, "Invalid amount of media types");
}
[Test]
public void CompareTo()
{
@@ -266,15 +253,15 @@ namespace Spring.Http
[Test]
public void CompareToConsistentWithEquals()
{
MediaType m1 = MediaType.ParseMediaType("text/html; q=0.7; charset=iso-8859-1");
MediaType m2 = MediaType.ParseMediaType("text/html; charset=iso-8859-1; q=0.7");
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.ParseMediaType("text/html; q=0.7; charset=iso-8859-1");
m2 = MediaType.ParseMediaType("text/html; Q=0.7; charset=iso-8859-1");
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");

View File

@@ -0,0 +1,48 @@
#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

@@ -2,7 +2,7 @@
#region License
/*
* Copyright 2002-2010 the original author or authors.
* 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.
@@ -91,7 +91,7 @@ namespace Spring.Http.Rest
}
[Test]
[ExpectedException(typeof(RestClientException),
[ExpectedException(typeof(HttpClientErrorException),
ExpectedMessage = "The server returned 'User with id '5' not found' with the status code 404 - NotFound.")]
public void GetStringError()
{
@@ -103,7 +103,7 @@ namespace Spring.Http.Rest
{
HttpResponseMessage<string> result = template.GetForMessage<string>("user/{id}", "1");
Assert.AreEqual("Bruno Baïa", result.Body, "Invalid content");
Assert.AreEqual(contentType, MediaType.ParseMediaType(result.Headers[HttpResponseHeader.ContentType]), "Invalid content-type");
Assert.AreEqual(contentType, result.Headers.ContentType, "Invalid content-type");
Assert.AreEqual(HttpStatusCode.OK, result.StatusCode, "Invalid status code");
Assert.AreEqual("OK", result.StatusDescription, "Invalid status description");
}
@@ -119,8 +119,8 @@ namespace Spring.Http.Rest
[Test]
public void HeadForHeaders()
{
WebHeaderCollection result = template.HeadForHeaders("head");
Assert.AreEqual(new MediaType("text", "plain"), MediaType.ParseMediaType(result[HttpResponseHeader.ContentType]), "Invalid content-type");
HttpHeaders result = template.HeadForHeaders("head");
Assert.AreEqual(new MediaType("text", "plain"), result.ContentType, "Invalid content-type");
}
[Test]
@@ -134,7 +134,7 @@ namespace Spring.Http.Rest
public void PostStringForMessage()
{
HttpResponseMessage<string> result = template.PostForMessage<string>("user", "Lisa Baia");
Assert.AreEqual(new Uri(new Uri(uri), "/user/3"), new Uri(result.Headers[HttpResponseHeader.Location]), "Invalid location");
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");
@@ -148,13 +148,21 @@ namespace Spring.Http.Rest
}
[Test]
[ExpectedException(typeof(RestClientException),
[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()
{
@@ -168,7 +176,7 @@ namespace Spring.Http.Rest
}
[Test]
[ExpectedException(typeof(RestClientException),
[ExpectedException(typeof(HttpClientErrorException),
ExpectedMessage = "The server returned 'User id '4' does not exist' with the status code 400 - BadRequest.")]
public void PutWithError()
{
@@ -188,7 +196,7 @@ namespace Spring.Http.Rest
}
[Test]
[ExpectedException(typeof(RestClientException),
[ExpectedException(typeof(HttpClientErrorException),
ExpectedMessage = "The server returned 'User id '10' does not exist' with the status code 400 - BadRequest.")]
public void DeleteWithError()
{
@@ -206,10 +214,10 @@ namespace Spring.Http.Rest
}
[Test]
public void ExchangePost()
public void ExchangeForResponse()
{
HttpResponseMessage<string> result = template.Exchange<string>(
"user", new HttpRequestMessage("Maryse Baia", HttpMethod.POST));
"user", HttpMethod.POST, new HttpEntity("Maryse Baia"));
Assert.AreEqual("3", result.Body, "Invalid content");
Assert.AreEqual(HttpStatusCode.Created, result.StatusCode, "Invalid status code");
@@ -217,27 +225,64 @@ namespace Spring.Http.Rest
}
[Test]
public void ExchangePut()
public void ExchangeForMessage()
{
HttpResponseMessage result = template.Exchange(
"user/1", new HttpRequestMessage("Bruno Baia", HttpMethod.PUT));
"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]
[ExpectedException(ExpectedMessage = "The server returned 'Not Found' with the status code 404 - NotFound.")]
public void ClientError()
public void ExchangeWithHeaders()
{
template.Execute<object>("clienterror", null, null);
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(ExpectedMessage = "The server returned 'Internal Server Error' with the status code 500 - InternalServerError.")]
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.")]
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", null, null);
template.Execute<object>("servererror", HttpMethod.GET, null, null);
}
#region REST test service
@@ -315,11 +360,12 @@ namespace Spring.Http.Rest
UriTemplateMatch match = context.IncomingRequest.UriTemplateMatch;
UriTemplate template = new UriTemplate("/user/{id}");
MediaType mediaType = MediaType.ParseMediaType(context.IncomingRequest.ContentType);
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.GetEncoding(mediaType.CharSet)))
using (StreamReader reader = new StreamReader(stream, encoding))
{
name = reader.ReadToEnd();
}
@@ -352,7 +398,7 @@ namespace Spring.Http.Rest
return;
}
MediaType mediaType = MediaType.ParseMediaType(context.IncomingRequest.ContentType);
MediaType mediaType = MediaType.Parse(context.IncomingRequest.ContentType);
string name;
using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding(mediaType.CharSet)))

View File

@@ -1,7 +1,7 @@
#region License
/*
* Copyright 2002-2010 the original author or authors.
* 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.
@@ -19,9 +19,11 @@
#endregion
using System;
using System.IO;
using System.Net;
using System.Collections.Generic;
using Spring.Http.Client;
using Spring.Http.Converters;
using NUnit.Framework;
@@ -45,20 +47,20 @@ namespace Spring.Http.Rest
private MockRepository mocks;
private RestTemplate template;
private IHttpWebRequestFactory requestFactory;
private HttpWebRequest request;
private HttpWebResponse response;
//private ResponseErrorHandler errorHandler;
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<IHttpWebRequestFactory>();
request = mocks.CreateMock<HttpWebRequest>();
response = mocks.CreateMock<HttpWebResponse>();
//errorHandler = createMock(ResponseErrorHandler.class);
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);
@@ -67,7 +69,7 @@ namespace Spring.Http.Rest
template = new RestTemplate();
template.RequestFactory = requestFactory;
template.MessageConverters = messageConverters;
//template.setErrorHandler(errorHandler);
template.ErrorHandler = errorHandler;
}
[TearDown]
@@ -79,44 +81,44 @@ namespace Spring.Http.Rest
[Test]
public void VarArgsTemplateVariables()
{
Expect.Call<HttpWebRequest>(requestFactory.CreateRequest(new Uri("http://example.com/hotels/42/bookings/21")))
Expect.Call<IClientHttpRequest>(requestFactory.CreateRequest(new Uri("http://example.com/hotels/42/bookings/21"), HttpMethod.GET))
.Return(request);
ExpectGetResponse();
//Expect.Call(errorHandler.hasError(response)).andReturn(false);
Expect.Call<bool>(errorHandler.HasError(response)).Return(false);
mocks.ReplayAll();
template.Execute<object>("http://example.com/hotels/{hotel}/bookings/{booking}", null, null, "42", "21");
template.Execute<object>("http://example.com/hotels/{hotel}/bookings/{booking}", HttpMethod.GET, null, null, "42", "21");
}
[Test]
public void DictionaryTemplateVariables()
{
Expect.Call<HttpWebRequest>(requestFactory.CreateRequest(new Uri("http://example.com/hotels/42/bookings/21")))
Expect.Call<IClientHttpRequest>(requestFactory.CreateRequest(new Uri("http://example.com/hotels/42/bookings/21"), HttpMethod.GET))
.Return(request);
ExpectGetResponse();
//Expect.Call(errorHandler.hasError(response)).andReturn(false);
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}", null, null, "42", "21");
template.Execute<object>("http://example.com/hotels/{hotel}/bookings/{booking}", HttpMethod.GET, null, null, "42", "21");
}
[Test]
public void BaseAddressTemplate()
{
Expect.Call<HttpWebRequest>(requestFactory.CreateRequest(new Uri("http://example.com/hotels/42/bookings/21")))
Expect.Call<IClientHttpRequest>(requestFactory.CreateRequest(new Uri("http://example.com/hotels/42/bookings/21"), HttpMethod.GET))
.Return(request);
ExpectGetResponse();
//Expect.Call(errorHandler.hasError(response)).andReturn(false);
Expect.Call<bool>(errorHandler.HasError(response)).Return(false);
mocks.ReplayAll();
template.BaseAddress = new Uri("http://example.com");
template.Execute<object>("hotels/{hotel}/bookings/{booking}", null, null, "42", "21");
template.Execute<object>("hotels/{hotel}/bookings/{booking}", HttpMethod.GET, null, null, "42", "21");
}
//[Test]
@@ -150,17 +152,14 @@ namespace Spring.Http.Rest
IList<MediaType> mediaTypes = new List<MediaType>(1);
mediaTypes.Add(textPlain);
Expect.Call<IList<MediaType>>(converter.SupportedMediaTypes).Return(mediaTypes);
Expect.Call<HttpWebRequest>(requestFactory.CreateRequest(new Uri("http://example.com"))).Return(request);
Expect.Call(request.Method = "GET");
Expect.Call(request.Accept = "text/plain");
WebHeaderCollection requestHeaders = new WebHeaderCollection();
Expect.Call<WebHeaderCollection>(request.Headers).Return(requestHeaders).Repeat.Any();
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(errorHandler.hasError(response)).andReturn(false);
//Expect.Call<string>(response.ContentType).Return(textPlain.ToString()).Repeat.AtLeastOnce();
WebHeaderCollection responseHeaders = new WebHeaderCollection();
responseHeaders[HttpResponseHeader.ContentType] = textPlain.ToString();
Expect.Call<WebHeaderCollection>(response.Headers).Return(responseHeaders).Repeat.Any();
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);
@@ -169,6 +168,7 @@ namespace Spring.Http.Rest
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]
@@ -181,17 +181,15 @@ namespace Spring.Http.Rest
IList<MediaType> mediaTypes = new List<MediaType>(1);
mediaTypes.Add(textPlain);
Expect.Call<IList<MediaType>>(converter.SupportedMediaTypes).Return(mediaTypes);
Expect.Call<HttpWebRequest>(requestFactory.CreateRequest(new Uri("http://example.com/resource"))).Return(request);
Expect.Call(request.Method = "GET");
Expect.Call(request.Accept = "foo/bar");
WebHeaderCollection requestHeaders = new WebHeaderCollection();
Expect.Call<WebHeaderCollection>(request.Headers).Return(requestHeaders).Repeat.Any();
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(errorHandler.hasError(response)).andReturn(false);
WebHeaderCollection responseHeaders = new WebHeaderCollection();
Expect.Call<bool>(errorHandler.HasError(response)).Return(false);
HttpHeaders responseHeaders = new HttpHeaders();
MediaType contentType = new MediaType("bar", "baz");
responseHeaders[HttpResponseHeader.ContentType] = contentType.ToString();
Expect.Call<WebHeaderCollection>(response.Headers).Return(responseHeaders).Repeat.Any();
responseHeaders.ContentType = contentType;
Expect.Call<HttpHeaders>(response.Headers).Return(responseHeaders).Repeat.Any();
Expect.Call<bool>(converter.CanRead(typeof(string), contentType)).Return(false);
mocks.ReplayAll();
@@ -207,16 +205,14 @@ namespace Spring.Http.Rest
IList<MediaType> mediaTypes = new List<MediaType>(1);
mediaTypes.Add(textPlain);
Expect.Call<IList<MediaType>>(converter.SupportedMediaTypes).Return(mediaTypes);
Expect.Call<HttpWebRequest>(requestFactory.CreateRequest(new Uri("http://example.com"))).Return(request);
Expect.Call(request.Method = "GET");
Expect.Call(request.Accept = "text/plain");
WebHeaderCollection requestHeaders = new WebHeaderCollection();
Expect.Call<WebHeaderCollection>(request.Headers).Return(requestHeaders).Repeat.Any();
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(errorHandler.hasError(response)).andReturn(false);
WebHeaderCollection responseHeaders = new WebHeaderCollection();
responseHeaders[HttpResponseHeader.ContentType] = textPlain.ToString();
Expect.Call<WebHeaderCollection>(response.Headers).Return(responseHeaders).Repeat.Any();
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);
@@ -227,7 +223,8 @@ namespace Spring.Http.Rest
HttpResponseMessage<String> result = template.GetForMessage<string>("http://example.com");
Assert.AreEqual(expected, result.Body, "Invalid GET result");
Assert.AreEqual(textPlain.ToString(), result.Headers[HttpResponseHeader.ContentType], "Invalid Content-Type header");
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");
@@ -237,16 +234,15 @@ namespace Spring.Http.Rest
[Test]
public void HeadForHeaders()
{
Expect.Call<HttpWebRequest>(requestFactory.CreateRequest(new Uri("http://example.com"))).Return(request);
Expect.Call(request.Method = "HEAD");
Expect.Call<IClientHttpRequest>(requestFactory.CreateRequest(new Uri("http://example.com"), HttpMethod.HEAD)).Return(request);
ExpectGetResponse();
//Expect.Call(errorHandler.hasError(response)).andReturn(false);
WebHeaderCollection responseHeaders = new WebHeaderCollection();
Expect.Call<WebHeaderCollection>(response.Headers).Return(responseHeaders).Repeat.Any();
Expect.Call<bool>(errorHandler.HasError(response)).Return(false);
HttpHeaders responseHeaders = new HttpHeaders();
Expect.Call<HttpHeaders>(response.Headers).Return(responseHeaders).Repeat.Any();
mocks.ReplayAll();
WebHeaderCollection result = template.HeadForHeaders("http://example.com");
HttpHeaders result = template.HeadForHeaders("http://example.com");
Assert.AreSame(responseHeaders, result, "Invalid headers returned");
}
@@ -255,16 +251,15 @@ namespace Spring.Http.Rest
public void PostForLocation()
{
string helloWorld = "Hello World";
Expect.Call<HttpWebRequest>(requestFactory.CreateRequest(new Uri("http://example.com"))).Return(request);
Expect.Call(request.Method = "POST");
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(errorHandler.hasError(response)).andReturn(false);
WebHeaderCollection responseHeaders = new WebHeaderCollection();
Expect.Call<bool>(errorHandler.HasError(response)).Return(false);
HttpHeaders responseHeaders = new HttpHeaders();
Uri expected = new Uri("http://example.com/hotels");
responseHeaders[HttpResponseHeader.Location] = expected.ToString();
Expect.Call<WebHeaderCollection>(response.Headers).Return(responseHeaders).Repeat.Any();
responseHeaders.Location = expected;
Expect.Call<HttpHeaders>(response.Headers).Return(responseHeaders).Repeat.Any();
mocks.ReplayAll();
@@ -276,28 +271,26 @@ namespace Spring.Http.Rest
public void PostForLocationMessageContentType()
{
string helloWorld = "Hello World";
Expect.Call<HttpWebRequest>(requestFactory.CreateRequest(new Uri("http://example.com"))).Return(request);
Expect.Call(request.Method = "POST");
Expect.Call<IClientHttpRequest>(requestFactory.CreateRequest(new Uri("http://example.com"), HttpMethod.POST)).Return(request);
MediaType contentType = new MediaType("text", "plain");
Expect.Call(request.ContentType = contentType.ToString());
Expect.Call<bool>(converter.CanWrite(typeof(string), contentType)).Return(true);
WebHeaderCollection requestHeaders = new WebHeaderCollection();
Expect.Call<WebHeaderCollection>(request.Headers).Return(requestHeaders).Repeat.Any();
HttpHeaders requestHeaders = new HttpHeaders();
Expect.Call<HttpHeaders>(request.Headers).Return(requestHeaders).Repeat.Any();
converter.Write(helloWorld, contentType, request);
ExpectGetResponse();
//Expect.Call(errorHandler.hasError(response)).andReturn(false);
WebHeaderCollection responseHeaders = new WebHeaderCollection();
Expect.Call<bool>(errorHandler.HasError(response)).Return(false);
HttpHeaders responseHeaders = new HttpHeaders();
Uri expected = new Uri("http://example.com/hotels");
responseHeaders[HttpResponseHeader.Location] = expected.ToString();
Expect.Call<WebHeaderCollection>(response.Headers).Return(responseHeaders).Repeat.Any();
responseHeaders.Location = expected;
Expect.Call<HttpHeaders>(response.Headers).Return(responseHeaders).Repeat.Any();
mocks.ReplayAll();
WebHeaderCollection requestMessageHeaders = new WebHeaderCollection();
requestMessageHeaders[HttpRequestHeader.ContentType] = contentType.ToString();
HttpRequestMessage requestMessage = new HttpRequestMessage(helloWorld, requestMessageHeaders);
HttpHeaders entityHeaders = new HttpHeaders();
entityHeaders.ContentType = contentType;
HttpEntity entity = new HttpEntity(helloWorld, entityHeaders);
Uri result = template.PostForLocation("http://example.com", requestMessage);
Uri result = template.PostForLocation("http://example.com", entity);
Assert.AreEqual(expected, result, "Invalid POST result");
}
@@ -305,26 +298,25 @@ namespace Spring.Http.Rest
public void PostForLocationMessageCustomHeader()
{
string helloWorld = "Hello World";
Expect.Call<HttpWebRequest>(requestFactory.CreateRequest(new Uri("http://example.com"))).Return(request);
Expect.Call(request.Method = "POST");
Expect.Call<IClientHttpRequest>(requestFactory.CreateRequest(new Uri("http://example.com"), HttpMethod.POST)).Return(request);
Expect.Call<bool>(converter.CanWrite(typeof(string), null)).Return(true);
WebHeaderCollection requestHeaders = new WebHeaderCollection();
Expect.Call<WebHeaderCollection>(request.Headers).Return(requestHeaders).Repeat.Any();
HttpHeaders requestHeaders = new HttpHeaders();
Expect.Call<HttpHeaders>(request.Headers).Return(requestHeaders).Repeat.Any();
converter.Write(helloWorld, null, request);
ExpectGetResponse();
//Expect.Call(errorHandler.hasError(response)).andReturn(false);
WebHeaderCollection responseHeaders = new WebHeaderCollection();
Expect.Call<bool>(errorHandler.HasError(response)).Return(false);
HttpHeaders responseHeaders = new HttpHeaders();
Uri expected = new Uri("http://example.com/hotels");
responseHeaders[HttpResponseHeader.Location] = expected.ToString();
Expect.Call<WebHeaderCollection>(response.Headers).Return(responseHeaders).Repeat.Any();
responseHeaders.Location = expected;
Expect.Call<HttpHeaders>(response.Headers).Return(responseHeaders).Repeat.Any();
mocks.ReplayAll();
WebHeaderCollection requestMessageHeaders = new WebHeaderCollection();
requestMessageHeaders.Add("MyHeader", "MyValue");
HttpRequestMessage requestMessage = new HttpRequestMessage(helloWorld, requestMessageHeaders);
HttpHeaders entityHeaders = new HttpHeaders();
entityHeaders.Add("MyHeader", "MyValue");
HttpEntity entity = new HttpEntity(helloWorld, entityHeaders);
Uri result = template.PostForLocation("http://example.com", requestMessage);
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");
}
@@ -333,14 +325,13 @@ namespace Spring.Http.Rest
public void PostForLocationNoLocation()
{
string helloWorld = "Hello World";
Expect.Call<HttpWebRequest>(requestFactory.CreateRequest(new Uri("http://example.com"))).Return(request);
Expect.Call(request.Method = "POST");
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(errorHandler.hasError(response)).andReturn(false);
WebHeaderCollection responseHeaders = new WebHeaderCollection();
Expect.Call<WebHeaderCollection>(response.Headers).Return(responseHeaders).Repeat.Any();
Expect.Call<bool>(errorHandler.HasError(response)).Return(false);
HttpHeaders responseHeaders = new HttpHeaders();
Expect.Call<HttpHeaders>(response.Headers).Return(responseHeaders).Repeat.Any();
mocks.ReplayAll();
@@ -353,19 +344,19 @@ namespace Spring.Http.Rest
[Test]
public void PostForLocationNull()
{
Expect.Call<HttpWebRequest>(requestFactory.CreateRequest(new Uri("http://example.com"))).Return(request);
Expect.Call(request.Method = "POST");
WebHeaderCollection requestHeaders = new WebHeaderCollection();
Expect.Call<WebHeaderCollection>(request.Headers).Return(requestHeaders).Repeat.Any();
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(errorHandler.hasError(response)).andReturn(false);
WebHeaderCollection responseHeaders = new WebHeaderCollection();
Expect.Call<WebHeaderCollection>(response.Headers).Return(responseHeaders).Repeat.Any();
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.IsNull(requestHeaders[HttpRequestHeader.ContentLength], "Invalid content length");
Assert.AreEqual(0, requestHeaders.ContentLength, "Invalid content length");
}
[Test]
@@ -376,19 +367,17 @@ namespace Spring.Http.Rest
IList<MediaType> mediaTypes = new List<MediaType>(1);
mediaTypes.Add(textPlain);
Expect.Call<IList<MediaType>>(converter.SupportedMediaTypes).Return(mediaTypes);
Expect.Call<HttpWebRequest>(requestFactory.CreateRequest(new Uri("http://example.com"))).Return(request);
Expect.Call(request.Method = "POST");
Expect.Call(request.Accept = "text/plain");
WebHeaderCollection requestHeaders = new WebHeaderCollection();
Expect.Call<WebHeaderCollection>(request.Headers).Return(requestHeaders).Repeat.Any();
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(errorHandler.hasError(response)).andReturn(false);
WebHeaderCollection responseHeaders = new WebHeaderCollection();
responseHeaders[HttpResponseHeader.ContentType] = textPlain.ToString();
Expect.Call<WebHeaderCollection>(response.Headers).Return(responseHeaders).Repeat.Any();
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);
@@ -397,6 +386,7 @@ namespace Spring.Http.Rest
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]
@@ -407,19 +397,17 @@ namespace Spring.Http.Rest
IList<MediaType> mediaTypes = new List<MediaType>(1);
mediaTypes.Add(textPlain);
Expect.Call<IList<MediaType>>(converter.SupportedMediaTypes).Return(mediaTypes);
Expect.Call<HttpWebRequest>(requestFactory.CreateRequest(new Uri("http://example.com"))).Return(request);
Expect.Call(request.Method = "POST");
Expect.Call(request.Accept = "text/plain");
WebHeaderCollection requestHeaders = new WebHeaderCollection();
Expect.Call<WebHeaderCollection>(request.Headers).Return(requestHeaders).Repeat.Any();
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(errorHandler.hasError(response)).andReturn(false);
WebHeaderCollection responseHeaders = new WebHeaderCollection();
responseHeaders[HttpResponseHeader.ContentType] = textPlain.ToString();
Expect.Call<WebHeaderCollection>(response.Headers).Return(responseHeaders).Repeat.Any();
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);
@@ -430,7 +418,8 @@ namespace Spring.Http.Rest
HttpResponseMessage<Version> result = template.PostForMessage<Version>("http://example.com", helloWorld);
Assert.AreEqual(expected, result.Body, "Invalid POST result");
Assert.AreEqual(textPlain, MediaType.ParseMediaType(result.Headers[HttpResponseHeader.ContentType]), "Invalid Content-Type");
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");
}
@@ -438,17 +427,16 @@ namespace Spring.Http.Rest
[Test]
public void PostForMessageNoBody()
{
Expect.Call<HttpWebRequest>(requestFactory.CreateRequest(new Uri("http://example.com"))).Return(request);
Expect.Call(request.Method = "POST");
WebHeaderCollection requestHeaders = new WebHeaderCollection();
Expect.Call<WebHeaderCollection>(request.Headers).Return(requestHeaders).Repeat.Any();
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(errorHandler.hasError(response)).andReturn(false);
WebHeaderCollection responseHeaders = new WebHeaderCollection();
Expect.Call<WebHeaderCollection>(response.Headers).Return(responseHeaders);
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");
@@ -468,16 +456,14 @@ namespace Spring.Http.Rest
IList<MediaType> mediaTypes = new List<MediaType>(1);
mediaTypes.Add(textPlain);
Expect.Call<IList<MediaType>>(converter.SupportedMediaTypes).Return(mediaTypes);
Expect.Call<HttpWebRequest>(requestFactory.CreateRequest(new Uri("http://example.com"))).Return(request);
Expect.Call(request.Method = "POST");
Expect.Call(request.Accept = "text/plain");
WebHeaderCollection requestHeaders = new WebHeaderCollection();
Expect.Call<WebHeaderCollection>(request.Headers).Return(requestHeaders).Repeat.Any();
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(errorHandler.hasError(response)).andReturn(false);
WebHeaderCollection responseHeaders = new WebHeaderCollection();
responseHeaders[HttpResponseHeader.ContentType] = textPlain.ToString();
Expect.Call<WebHeaderCollection>(response.Headers).Return(responseHeaders).Repeat.Any();
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);
@@ -485,7 +471,9 @@ namespace Spring.Http.Rest
Version result = template.PostForObject<Version>("http://example.com", null);
Assert.IsNull(result, "Invalid POST result");
Assert.IsNull(requestHeaders[HttpRequestHeader.ContentLength], "Invalid content length");
Assert.AreEqual(textPlain.ToString(), requestHeaders.GetSingleValue("Accept"), "Invalid Accept header");
Assert.AreEqual(0, requestHeaders.ContentLength, "Invalid content length");
}
[Test]
@@ -496,16 +484,14 @@ namespace Spring.Http.Rest
IList<MediaType> mediaTypes = new List<MediaType>(1);
mediaTypes.Add(textPlain);
Expect.Call<IList<MediaType>>(converter.SupportedMediaTypes).Return(mediaTypes);
Expect.Call<HttpWebRequest>(requestFactory.CreateRequest(new Uri("http://example.com"))).Return(request);
Expect.Call(request.Method = "POST");
Expect.Call(request.Accept = "text/plain");
WebHeaderCollection requestHeaders = new WebHeaderCollection();
Expect.Call<WebHeaderCollection>(request.Headers).Return(requestHeaders).Repeat.Any();
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(errorHandler.hasError(response)).andReturn(false);
WebHeaderCollection responseHeaders = new WebHeaderCollection();
responseHeaders[HttpResponseHeader.ContentType] = textPlain.ToString();
Expect.Call<WebHeaderCollection>(response.Headers).Return(responseHeaders).Repeat.Any();
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);
@@ -515,8 +501,10 @@ namespace Spring.Http.Rest
HttpResponseMessage<Version> result = template.PostForMessage<Version>("http://example.com", null);
Assert.IsNull(result.Body, "Invalid POST result");
Assert.AreEqual(textPlain, MediaType.ParseMediaType(result.Headers[HttpResponseHeader.ContentType]), "Invalid Content-Type");
Assert.IsNull(requestHeaders[HttpRequestHeader.ContentLength], "Invalid content length");
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");
}
@@ -525,12 +513,11 @@ namespace Spring.Http.Rest
public void Put()
{
Expect.Call<bool>(converter.CanWrite(typeof(string), null)).Return(true);
Expect.Call<HttpWebRequest>(requestFactory.CreateRequest(new Uri("http://example.com"))).Return(request);
Expect.Call(request.Method = "PUT");
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(errorHandler.hasError(response)).andReturn(false);
Expect.Call<bool>(errorHandler.HasError(response)).Return(false);
mocks.ReplayAll();
@@ -540,27 +527,25 @@ namespace Spring.Http.Rest
[Test]
public void PutNull()
{
Expect.Call<HttpWebRequest>(requestFactory.CreateRequest(new Uri("http://example.com"))).Return(request);
Expect.Call(request.Method = "PUT");
WebHeaderCollection requestHeaders = new WebHeaderCollection();
Expect.Call<WebHeaderCollection>(request.Headers).Return(requestHeaders).Repeat.Any();
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(errorHandler.hasError(response)).andReturn(false);
Expect.Call<bool>(errorHandler.HasError(response)).Return(false);
mocks.ReplayAll();
template.Put("http://example.com", null);
Assert.IsNull(requestHeaders[HttpRequestHeader.ContentLength], "Invalid content length");
Assert.AreEqual(0, requestHeaders.ContentLength, "Invalid content length");
}
[Test]
public void Delete()
{
Expect.Call<HttpWebRequest>(requestFactory.CreateRequest(new Uri("http://example.com"))).Return(request);
Expect.Call(request.Method = "DELETE");
Expect.Call<IClientHttpRequest>(requestFactory.CreateRequest(new Uri("http://example.com"), HttpMethod.DELETE)).Return(request);
ExpectGetResponse();
//Expect.Call(errorHandler.hasError(response)).andReturn(false);
Expect.Call<bool>(errorHandler.HasError(response)).Return(false);
mocks.ReplayAll();
@@ -570,13 +555,13 @@ namespace Spring.Http.Rest
[Test]
public void OptionsForAllow()
{
Expect.Call<HttpWebRequest>(requestFactory.CreateRequest(new Uri("http://example.com"))).Return(request);
Expect.Call(request.Method = "OPTIONS");
Expect.Call<IClientHttpRequest>(requestFactory.CreateRequest(new Uri("http://example.com"), HttpMethod.OPTIONS)).Return(request);
ExpectGetResponse();
//Expect.Call(errorHandler.hasError(response)).andReturn(false);
WebHeaderCollection responseHeaders = new WebHeaderCollection();
responseHeaders[HttpResponseHeader.Allow] = "GET,POST";
Expect.Call<WebHeaderCollection>(response.Headers).Return(responseHeaders).Repeat.Any();
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();
@@ -616,19 +601,17 @@ namespace Spring.Http.Rest
IList<MediaType> mediaTypes = new List<MediaType>(1);
mediaTypes.Add(textPlain);
Expect.Call<IList<MediaType>>(converter.SupportedMediaTypes).Return(mediaTypes);
Expect.Call<HttpWebRequest>(requestFactory.CreateRequest(new Uri("http://example.com"))).Return(request);
Expect.Call(request.Method = "POST");
Expect.Call(request.Accept = "text/plain");
WebHeaderCollection requestHeaders = new WebHeaderCollection();
Expect.Call<WebHeaderCollection>(request.Headers).Return(requestHeaders).Repeat.Any();
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(errorHandler.hasError(response)).andReturn(false);
WebHeaderCollection responseHeaders = new WebHeaderCollection();
responseHeaders[HttpResponseHeader.ContentType] = textPlain.ToString();
Expect.Call<WebHeaderCollection>(response.Headers).Return(responseHeaders).Repeat.Any();
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);
@@ -637,12 +620,13 @@ namespace Spring.Http.Rest
mocks.ReplayAll();
WebHeaderCollection requestMessageHeaders = new WebHeaderCollection();
HttpHeaders requestMessageHeaders = new HttpHeaders();
requestMessageHeaders.Add("MyHeader", "MyValue");
HttpRequestMessage requestMessage = new HttpRequestMessage(helloWorld, requestMessageHeaders, HttpMethod.POST);
HttpResponseMessage<Version> result = template.Exchange<Version>("http://example.com", requestMessage);
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, MediaType.ParseMediaType(result.Headers[HttpResponseHeader.ContentType]), "Invalid Content-Type");
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");
@@ -652,7 +636,7 @@ namespace Spring.Http.Rest
private void ExpectGetResponse()
{
Expect.Call<WebResponse>(request.GetResponse()).Return(response);
Expect.Call<IClientHttpResponse>(request.Execute()).Return(response);
#region Instrumentation
if (LOG.IsDebugEnabled)
{
@@ -660,8 +644,7 @@ namespace Spring.Http.Rest
Expect.Call<string>(response.StatusDescription).Return("OK");
}
#endregion
Expect.Call(response.Close);
Expect.Call<bool>(request.HaveResponse).Return(true);
Expect.Call(response.Dispose);
}
#endregion

View File

@@ -91,7 +91,7 @@
<ItemGroup>
<Compile Include="AssemblyInfo.cs" />
<Compile Include="Http\Converters\ByteArrayHttpMessageConverterTests.cs" />
<Compile Include="Http\Converters\UrlEncodedFormHttpMessageConverterTests.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" />
@@ -103,8 +103,11 @@
<Compile Include="Http\Converters\Xml\XmlDocumentHttpMessageConverterTests.cs" />
<Compile Include="Http\Converters\Xml\XmlHttpMessageConverterIntegrationTests.cs" />
<Compile Include="Http\Converters\Xml\XmlSerializableHttpMessageConverterTests.cs" />
<Compile Include="Http\HttpHeadersTests.cs" />
<Compile Include="Http\MediaTypeTests.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>

View File

@@ -0,0 +1,79 @@
<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

@@ -107,10 +107,12 @@
<ItemGroup>
<Compile Include="AssemblyInfo.cs" />
<Compile Include="Http\Converters\ByteArrayHttpMessageConverterTests.cs" />
<Compile Include="Http\Converters\UrlEncodedFormHttpMessageConverterTests.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" />
@@ -119,8 +121,11 @@
<Compile Include="Http\Converters\Xml\XmlDocumentHttpMessageConverterTests.cs" />
<Compile Include="Http\Converters\Xml\XmlHttpMessageConverterIntegrationTests.cs" />
<Compile Include="Http\Converters\Xml\XmlSerializableHttpMessageConverterTests.cs" />
<Compile Include="Http\HttpHeadersTests.cs" />
<Compile Include="Http\MediaTypeTests.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>

View File

@@ -0,0 +1,94 @@
<?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

@@ -0,0 +1,75 @@
<?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

@@ -125,18 +125,23 @@
<SubType>Code</SubType>
</Compile>
<Compile Include="Http\Converters\Feed\Rss20FeedHttpMessageConverterTests.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\UrlEncodedFormHttpMessageConverterTests.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\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>

View File

@@ -0,0 +1,80 @@
#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,7 +1,7 @@
#region License
/*
* Copyright 2002-2010 the original author or authors.
* 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.