PageRenderTime 101ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 0ms

/wine-mono-0.0.4/mono/external/aspnetwebstack/test/System.Net.Http.Formatting.Test.Unit/HttpContentExtensionsTest.cs

#
C# | 230 lines | 187 code | 42 blank | 1 comment | 0 complexity | b34a7bdbc4937a873454fa3d3a3fb028 MD5 | raw file
Possible License(s): LGPL-2.1, GPL-2.0, Unlicense, BSD-3-Clause, MPL-2.0-no-copyleft-exception, CC-BY-SA-3.0, ISC, Apache-2.0, LGPL-2.0
  1. // Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Net.Http.Formatting;
  6. using System.Net.Http.Headers;
  7. using System.Threading.Tasks;
  8. using Moq;
  9. using Xunit;
  10. using Assert = Microsoft.TestCommon.AssertEx;
  11. namespace System.Net.Http
  12. {
  13. public class HttpContentExtensionsTest
  14. {
  15. private static readonly IEnumerable<MediaTypeFormatter> _emptyFormatterList = Enumerable.Empty<MediaTypeFormatter>();
  16. private readonly Mock<MediaTypeFormatter> _formatterMock = new Mock<MediaTypeFormatter> { CallBase = true };
  17. private readonly MediaTypeHeaderValue _mediaType = new MediaTypeHeaderValue("foo/bar");
  18. private readonly MediaTypeFormatter[] _formatters;
  19. public HttpContentExtensionsTest()
  20. {
  21. _formatterMock.Object.SupportedMediaTypes.Add(_mediaType);
  22. _formatters = new[] { _formatterMock.Object };
  23. }
  24. [Fact]
  25. public void ReadAsAsync_WhenContentParameterIsNull_Throws()
  26. {
  27. Assert.ThrowsArgumentNull(() => HttpContentExtensions.ReadAsAsync(null, typeof(string), _emptyFormatterList), "content");
  28. }
  29. [Fact]
  30. public void ReadAsAsync_WhenTypeParameterIsNull_Throws()
  31. {
  32. Assert.ThrowsArgumentNull(() => HttpContentExtensions.ReadAsAsync(new StringContent(""), null, _emptyFormatterList), "type");
  33. }
  34. [Fact]
  35. public void ReadAsAsync_WhenFormattersParameterIsNull_Throws()
  36. {
  37. Assert.ThrowsArgumentNull(() => HttpContentExtensions.ReadAsAsync(new StringContent(""), typeof(string), null), "formatters");
  38. }
  39. [Fact]
  40. public void ReadAsAsyncOfT_WhenContentParameterIsNull_Throws()
  41. {
  42. Assert.ThrowsArgumentNull(() => HttpContentExtensions.ReadAsAsync<string>(null, _emptyFormatterList), "content");
  43. }
  44. [Fact]
  45. public void ReadAsAsyncOfT_WhenFormattersParameterIsNull_Throws()
  46. {
  47. Assert.ThrowsArgumentNull(() => HttpContentExtensions.ReadAsAsync<string>(new StringContent(""), null), "formatters");
  48. }
  49. [Fact]
  50. public void ReadAsAsyncOfT_WhenContentIsObjectContent_GoesThroughSerializationCycleToConvertTypes()
  51. {
  52. var content = new ObjectContent<int[]>(new int[] { 10, 20, 30, 40 }, new JsonMediaTypeFormatter());
  53. byte[] result = content.ReadAsAsync<byte[]>().Result;
  54. Assert.Equal(new byte[] { 10, 20, 30, 40 }, result);
  55. }
  56. [Fact]
  57. public void ReadAsAsyncOfT_WhenNoMatchingFormatterFound_Throws()
  58. {
  59. var content = new StringContent("{}");
  60. content.Headers.ContentType = _mediaType;
  61. content.Headers.ContentType.CharSet = "utf-16";
  62. var formatters = new MediaTypeFormatter[] { new JsonMediaTypeFormatter() };
  63. Assert.Throws<InvalidOperationException>(() => content.ReadAsAsync<List<string>>(formatters),
  64. "No MediaTypeFormatter is available to read an object of type 'List`1' from content with media type 'foo/bar'.");
  65. }
  66. [Fact]
  67. public void ReadAsAsyncOfT_WhenNoMatchingFormatterFoundForContentWithNoMediaType_Throws()
  68. {
  69. var content = new StringContent("{}");
  70. content.Headers.ContentType = null;
  71. var formatters = new MediaTypeFormatter[] { new JsonMediaTypeFormatter() };
  72. Assert.Throws<InvalidOperationException>(() => content.ReadAsAsync<List<string>>(formatters),
  73. "No MediaTypeFormatter is available to read an object of type 'List`1' from content with media type ''undefined''.");
  74. }
  75. [Fact]
  76. public void ReadAsAsyncOfT_ReadsFromContent_ThenInvokesFormattersReadFromStreamMethod()
  77. {
  78. Stream contentStream = null;
  79. string value = "42";
  80. var contentMock = new Mock<TestableHttpContent> { CallBase = true };
  81. contentMock.Setup(c => c.SerializeToStreamAsyncPublic(It.IsAny<Stream>(), It.IsAny<TransportContext>()))
  82. .Returns(TaskHelpers.Completed)
  83. .Callback((Stream s, TransportContext _) => contentStream = s)
  84. .Verifiable();
  85. HttpContent content = contentMock.Object;
  86. content.Headers.ContentType = _mediaType;
  87. _formatterMock
  88. .Setup(f => f.ReadFromStreamAsync(typeof(string), It.IsAny<Stream>(), It.IsAny<HttpContentHeaders>(), It.IsAny<IFormatterLogger>()))
  89. .Returns(TaskHelpers.FromResult<object>(value));
  90. _formatterMock.Setup(f => f.CanReadType(typeof(string))).Returns(true);
  91. var result = content.ReadAsAsync<string>(_formatters);
  92. var resultValue = result.Result;
  93. Assert.Same(value, resultValue);
  94. contentMock.Verify();
  95. _formatterMock.Verify(f => f.ReadFromStreamAsync(typeof(string), contentStream, content.Headers, null), Times.Once());
  96. }
  97. [Fact]
  98. public void ReadAsAsyncOfT_InvokesFormatterEvenIfContentLengthIsZero()
  99. {
  100. var content = new StringContent("");
  101. _formatterMock.Setup(f => f.CanReadType(typeof(string))).Returns(true);
  102. _formatterMock.Object.SupportedMediaTypes.Add(content.Headers.ContentType);
  103. var result = content.ReadAsAsync<string>(_formatters);
  104. result.WaitUntilCompleted();
  105. _formatterMock.Verify(f => f.ReadFromStreamAsync(typeof(string), It.IsAny<Stream>(), content.Headers, It.IsAny<IFormatterLogger>()), Times.Once());
  106. }
  107. [Fact]
  108. public void ReadAsAsync_WhenContentIsObjectContentAndValueIsCompatibleType_ReadsValueFromObjectContent()
  109. {
  110. _formatterMock.Setup(f => f.CanWriteType(typeof(TestClass))).Returns(true);
  111. var value = new TestClass();
  112. var content = new ObjectContent<TestClass>(value, _formatterMock.Object);
  113. Assert.Same(value, content.ReadAsAsync<object>(_formatters).Result);
  114. Assert.Same(value, content.ReadAsAsync<TestClass>(_formatters).Result);
  115. Assert.Same(value, content.ReadAsAsync(typeof(object), _formatters).Result);
  116. Assert.Same(value, content.ReadAsAsync(typeof(TestClass), _formatters).Result);
  117. _formatterMock.Verify(f => f.ReadFromStreamAsync(It.IsAny<Type>(), It.IsAny<Stream>(), content.Headers, It.IsAny<IFormatterLogger>()), Times.Never());
  118. }
  119. [Fact]
  120. public void ReadAsAsync_WhenContentIsObjectContentAndValueIsNull_IfTypeIsNullable_SerializesAndDeserializesValue()
  121. {
  122. _formatterMock.Setup(f => f.CanWriteType(typeof(object))).Returns(true);
  123. _formatterMock.Setup(f => f.CanReadType(It.IsAny<Type>())).Returns(true);
  124. var content = new ObjectContent<object>(null, _formatterMock.Object);
  125. SetupUpRoundTripSerialization(type => null);
  126. Assert.Null(content.ReadAsAsync<object>(_formatters).Result);
  127. Assert.Null(content.ReadAsAsync<TestClass>(_formatters).Result);
  128. Assert.Null(content.ReadAsAsync<Nullable<int>>(_formatters).Result);
  129. Assert.Null(content.ReadAsAsync(typeof(object), _formatters).Result);
  130. Assert.Null(content.ReadAsAsync(typeof(TestClass), _formatters).Result);
  131. Assert.Null(content.ReadAsAsync(typeof(Nullable<int>), _formatters).Result);
  132. _formatterMock.Verify(f => f.ReadFromStreamAsync(It.IsAny<Type>(), It.IsAny<Stream>(), content.Headers, It.IsAny<IFormatterLogger>()), Times.Exactly(6));
  133. }
  134. [Fact]
  135. public void ReadAsAsync_WhenContentIsObjectContentAndValueIsNull_IfTypeIsNotNullable_SerializesAndDeserializesValue()
  136. {
  137. _formatterMock.Setup(f => f.CanWriteType(typeof(object))).Returns(true);
  138. _formatterMock.Setup(f => f.CanReadType(typeof(Int32))).Returns(true);
  139. var content = new ObjectContent<object>(null, _formatterMock.Object, _mediaType.MediaType);
  140. SetupUpRoundTripSerialization();
  141. Assert.IsType<Int32>(content.ReadAsAsync<Int32>(_formatters).Result);
  142. Assert.IsType<Int32>(content.ReadAsAsync(typeof(Int32), _formatters).Result);
  143. _formatterMock.Verify(f => f.ReadFromStreamAsync(It.IsAny<Type>(), It.IsAny<Stream>(), content.Headers, It.IsAny<IFormatterLogger>()), Times.Exactly(2));
  144. }
  145. [Fact]
  146. public void ReadAsAsync_WhenContentIsObjectContentAndValueIsNotCompatibleType_SerializesAndDeserializesValue()
  147. {
  148. _formatterMock.Setup(f => f.CanWriteType(typeof(TestClass))).Returns(true);
  149. _formatterMock.Setup(f => f.CanReadType(typeof(string))).Returns(true);
  150. var value = new TestClass();
  151. var content = new ObjectContent<TestClass>(value, _formatterMock.Object, _mediaType.MediaType);
  152. SetupUpRoundTripSerialization(type => new TestClass());
  153. Assert.Throws<InvalidCastException>(() => content.ReadAsAsync<string>(_formatters).RethrowFaultedTaskException());
  154. Assert.IsNotType<string>(content.ReadAsAsync(typeof(string), _formatters).Result);
  155. _formatterMock.Verify(f => f.ReadFromStreamAsync(It.IsAny<Type>(), It.IsAny<Stream>(), content.Headers, It.IsAny<IFormatterLogger>()), Times.Exactly(2));
  156. }
  157. private void SetupUpRoundTripSerialization(Func<Type, object> factory = null)
  158. {
  159. factory = factory ?? Activator.CreateInstance;
  160. _formatterMock.Setup(f => f.WriteToStreamAsync(It.IsAny<Type>(), It.IsAny<object>(), It.IsAny<Stream>(), It.IsAny<HttpContentHeaders>(), It.IsAny<TransportContext>()))
  161. .Returns(TaskHelpers.Completed());
  162. _formatterMock.Setup(f => f.ReadFromStreamAsync(It.IsAny<Type>(), It.IsAny<Stream>(), It.IsAny<HttpContentHeaders>(), It.IsAny<IFormatterLogger>()))
  163. .Returns<Type, Stream, HttpContentHeaders, IFormatterLogger>((type, stream, headers, logger) => TaskHelpers.FromResult<object>(factory(type)));
  164. }
  165. public class TestClass { }
  166. public abstract class TestableHttpContent : HttpContent
  167. {
  168. protected override Task<Stream> CreateContentReadStreamAsync()
  169. {
  170. return CreateContentReadStreamAsyncPublic();
  171. }
  172. public virtual Task<Stream> CreateContentReadStreamAsyncPublic()
  173. {
  174. return base.CreateContentReadStreamAsync();
  175. }
  176. protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
  177. {
  178. return SerializeToStreamAsyncPublic(stream, context);
  179. }
  180. public abstract Task SerializeToStreamAsyncPublic(Stream stream, TransportContext context);
  181. protected override bool TryComputeLength(out long length)
  182. {
  183. return TryComputeLengthPublic(out length);
  184. }
  185. public abstract bool TryComputeLengthPublic(out long length);
  186. }
  187. }
  188. }