public static MediaTypeFormatter CreateTracer(MediaTypeFormatter formatter, ITraceWriter traceWriter, HttpRequestMessage request) { // If we have been asked to wrap a tracer around a formatter, it could be // already wrapped, and there is nothing to do. But if we see it is a tracer // that is not associated with a request, we wrap it into a new tracer that // does have a request. The only formatter tracers without requests are the // ones in the default MediaTypeFormatterCollection in the HttpConfiguration. IFormatterTracer formatterTracer = formatter as IFormatterTracer; if (formatterTracer != null) { if (formatterTracer.Request == request) { return formatter; } formatter = formatterTracer.InnerFormatter; } MediaTypeFormatter tracer = null; // We special-case Xml, Json and FormUrlEncoded formatters because we expect to be able // to find them with IsAssignableFrom in the MediaTypeFormatterCollection. if (formatter is XmlMediaTypeFormatter) { tracer = new XmlMediaTypeFormatterTracer(formatter, traceWriter, request); } else if (formatter is JsonMediaTypeFormatter) { tracer = new JsonMediaTypeFormatterTracer(formatter, traceWriter, request); } else if (formatter is FormUrlEncodedMediaTypeFormatter) { tracer = new FormUrlEncodedMediaTypeFormatterTracer(formatter, traceWriter, request); } else if (formatter is BufferedMediaTypeFormatter) { tracer = new BufferedMediaTypeFormatterTracer(formatter, traceWriter, request); } else { tracer = new MediaTypeFormatterTracer(formatter, traceWriter, request); } // Copy SupportedMediaTypes and MediaTypeMappings because they are publically visible tracer.SupportedMediaTypes.Clear(); foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { tracer.SupportedMediaTypes.Add(mediaType); } tracer.MediaTypeMappings.Clear(); foreach (MediaTypeMapping mapping in formatter.MediaTypeMappings) { tracer.MediaTypeMappings.Add(mapping); } return tracer; }
public async Task ReadFromStreamAsync_LogErrorFromJsonRequestBody(IList <TraceRecord> expectedTraces, HttpRequestMessage request, string requestBody) { // Arrange var formatter = new JsonMediaTypeFormatter(); formatter.UseDataContractJsonSerializer = false; HttpContent content = new StringContent(requestBody); content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); var loggerMock = new Mock <IFormatterLogger>(); loggerMock.Setup(l => l.LogError(It.IsAny <string>(), It.IsAny <Exception>())); TestTraceWriter traceWriter = new TestTraceWriter(); var tracer = new MediaTypeFormatterTracer(formatter, traceWriter, request); // Act await tracer.ReadFromStreamAsync(typeof(SampleType), await content.ReadAsStreamAsync(), content, loggerMock.Object ); // Assert // Error must always be marked as handled at ReadFromStream in BaseJsonMediaTypeFormatters, // so it would not propagate to here. // Note that regarding the exception's comparison in the record we only compare its message, // because we cannot get the exact exception and message would be enough for logging. Assert.Equal <TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer() { IgnoreExceptionReference = true }); }
public void OnReadFromStreamAsync_Traces_And_Throws_When_Inner_Throws() { // Arrange InvalidOperationException exception = new InvalidOperationException("test"); Mock<MediaTypeFormatter> mockFormatter = new Mock<MediaTypeFormatter>() { CallBase = true }; mockFormatter.Setup( f => f.ReadFromStreamAsync(It.IsAny<Type>(), It.IsAny<Stream>(), It.IsAny<HttpContentHeaders>(), It.IsAny<IFormatterLogger>())).Throws(exception); TestTraceWriter traceWriter = new TestTraceWriter(); HttpRequestMessage request = new HttpRequestMessage(); request.Content = new StringContent(""); MediaTypeFormatterTracer tracer = new MediaTypeFormatterTracer(mockFormatter.Object, traceWriter, request); TraceRecord[] expectedTraces = new TraceRecord[] { new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "ReadFromStreamAsync" }, new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Error) { Kind = TraceKind.End, Operation = "ReadFromStreamAsync" } }; // Act Exception thrown = Assert.Throws<InvalidOperationException>(() => tracer.ReadFromStreamAsync(typeof(string), new MemoryStream(), request.Content.Headers, null)); // Assert Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer()); Assert.Same(exception, thrown); Assert.Same(exception, traceWriter.Traces[1].Exception); }
public async Task ReadFromStream_Traces() { // Arrange string contentType = "text/plain"; object value = new object(); CustomMediaTypeFormatter formatter = new CustomMediaTypeFormatter(value); formatter.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse(contentType)); TestTraceWriter traceWriter = new TestTraceWriter(); HttpRequestMessage request = new HttpRequestMessage(); request.Content = new StringContent("42", Encoding.Default, contentType); MediaTypeFormatterTracer tracer = new MediaTypeFormatterTracer(formatter, traceWriter, request); TraceRecord[] expectedTraces = new TraceRecord[] { new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "ReadFromStreamAsync" }, new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Info) { Kind = TraceKind.End, Operation = "ReadFromStreamAsync" } }; // Act object valueReturned = await request.Content.ReadAsAsync <object>(new[] { tracer }); // Assert Assert.Equal <TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer()); Assert.Equal(value, valueReturned); }
public async Task WriteToStream_Traces() { // Arrange object value = new object(); CustomMediaTypeFormatter formatter = new CustomMediaTypeFormatter(value); TestTraceWriter traceWriter = new TestTraceWriter(); HttpRequestMessage request = new HttpRequestMessage(); MediaTypeFormatterTracer tracer = new MediaTypeFormatterTracer(formatter, traceWriter, request); request.Content = new ObjectContent <object>(value, tracer); TraceRecord[] expectedTraces = new TraceRecord[] { new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "WriteToStreamAsync" }, new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Info) { Kind = TraceKind.End, Operation = "WriteToStreamAsync" } }; // Act await request.Content.CopyToAsync(new MemoryStream()); // Assert Assert.Equal <TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer()); }
public void GetPerRequestFormatterInstance_Returns_Tracing_MediaTypeFormatter() { // Arrange Mock <MediaTypeFormatter> mockReturnFormatter = new Mock <MediaTypeFormatter>() { CallBase = true }; Mock <MediaTypeFormatter> mockFormatter = new Mock <MediaTypeFormatter>() { CallBase = true }; mockFormatter.Setup( f => f.GetPerRequestFormatterInstance(It.IsAny <Type>(), It.IsAny <HttpRequestMessage>(), It.IsAny <MediaTypeHeaderValue>())).Returns(mockReturnFormatter.Object); TestTraceWriter traceWriter = new TestTraceWriter(); HttpRequestMessage request = new HttpRequestMessage(); MediaTypeFormatterTracer tracer = new MediaTypeFormatterTracer(mockFormatter.Object, traceWriter, request); // Act MediaTypeFormatter actualFormatter = tracer.GetPerRequestFormatterInstance(typeof(string), request, new MediaTypeHeaderValue("application/json")); // Assert Assert.IsAssignableFrom <IFormatterTracer>(actualFormatter); }
public void OnReadFromStreamAsync_Traces() { // Arrange Mock<MediaTypeFormatter> mockFormatter = new Mock<MediaTypeFormatter>() { CallBase = true }; mockFormatter.Setup( f => f.ReadFromStreamAsync(It.IsAny<Type>(), It.IsAny<Stream>(), It.IsAny<HttpContentHeaders>(), It.IsAny<IFormatterLogger>())). Returns(TaskHelpers.FromResult<object>("sampleValue")); TestTraceWriter traceWriter = new TestTraceWriter(); HttpRequestMessage request = new HttpRequestMessage(); request.Content = new StringContent(""); MediaTypeFormatterTracer tracer = new MediaTypeFormatterTracer(mockFormatter.Object, traceWriter, request); TraceRecord[] expectedTraces = new TraceRecord[] { new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "ReadFromStreamAsync" }, new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Info) { Kind = TraceKind.End, Operation = "ReadFromStreamAsync" } }; // Act Task<object> task = tracer.ReadFromStreamAsync(typeof(string), new MemoryStream(), request.Content.Headers, null); string result = task.Result as string; // Assert Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer()); Assert.Equal("sampleValue", result); }
public static MediaTypeFormatter CreateTracer(MediaTypeFormatter formatter, ITraceWriter traceWriter, HttpRequestMessage request) { // If we have been asked to wrap a tracer around a formatter, it could be // already wrapped, and there is nothing to do. But if we see it is a tracer // that is not associated with a request, we wrap it into a new tracer that // does have a request. The only formatter tracers without requests are the // ones in the default MediaTypeFormatterCollection in the HttpConfiguration. IFormatterTracer formatterTracer = formatter as IFormatterTracer; if (formatterTracer != null) { if (formatterTracer.Request == request) { return(formatter); } formatter = formatterTracer.InnerFormatter; } MediaTypeFormatter tracer = null; // We special-case Xml, Json and FormUrlEncoded formatters because we expect to be able // to find them with IsAssignableFrom in the MediaTypeFormatterCollection. if (formatter is XmlMediaTypeFormatter) { tracer = new XmlMediaTypeFormatterTracer(formatter, traceWriter, request); } else if (formatter is JsonMediaTypeFormatter) { tracer = new JsonMediaTypeFormatterTracer(formatter, traceWriter, request); } else if (formatter is FormUrlEncodedMediaTypeFormatter) { tracer = new FormUrlEncodedMediaTypeFormatterTracer(formatter, traceWriter, request); } else if (formatter is BufferedMediaTypeFormatter) { tracer = new BufferedMediaTypeFormatterTracer(formatter, traceWriter, request); } else { tracer = new MediaTypeFormatterTracer(formatter, traceWriter, request); } // Copy SupportedMediaTypes and MediaTypeMappings because they are publically visible tracer.SupportedMediaTypes.Clear(); foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { tracer.SupportedMediaTypes.Add(mediaType); } tracer.MediaTypeMappings.Clear(); foreach (MediaTypeMapping mapping in formatter.MediaTypeMappings) { tracer.MediaTypeMappings.Add(mapping); } return(tracer); }
public override MediaTypeFormatter GetPerRequestFormatterInstance( Type type, HttpRequestMessage request, MediaTypeHeaderValue mediaType ) { MediaTypeFormatter formatter = null; TraceWriter.TraceBeginEnd( request, TraceCategories.FormattingCategory, TraceLevel.Info, InnerFormatter.GetType().Name, GetPerRequestFormatterInstanceMethodName, beginTrace: (tr) => { tr.Message = Error.Format( SRResources.TraceGetPerRequestFormatterMessage, InnerFormatter.GetType().Name, type.Name, mediaType ); }, execute: () => { formatter = InnerFormatter.GetPerRequestFormatterInstance( type, request, mediaType ); }, endTrace: (tr) => { if (formatter == null) { tr.Message = SRResources.TraceGetPerRequestNullFormatterEndMessage; } else { string formatMessage = Object.ReferenceEquals( MediaTypeFormatterTracer.ActualMediaTypeFormatter(formatter), InnerFormatter ) ? SRResources.TraceGetPerRequestFormatterEndMessage : SRResources.TraceGetPerRequestFormatterEndMessageNew; tr.Message = Error.Format(formatMessage, formatter.GetType().Name); } }, errorTrace: null ); if (formatter != null && !(formatter is IFormatterTracer)) { formatter = MediaTypeFormatterTracer.CreateTracer(formatter, TraceWriter, request); } return(formatter); }
public BufferedMediaTypeFormatterTracer(BufferedMediaTypeFormatter innerFormatter, ITraceWriter traceWriter, HttpRequestMessage request) { _innerTracer = new MediaTypeFormatterTracer(innerFormatter, traceWriter, request); // copy non-overridable members from inner formatter _innerTracer.CopyNonOverriableMembersFromInner(this); BufferSize = innerFormatter.BufferSize; }
public FormUrlEncodedMediaTypeFormatterTracer(FormUrlEncodedMediaTypeFormatter innerFormatter, ITraceWriter traceWriter, HttpRequestMessage request) { _innerTracer = new MediaTypeFormatterTracer(innerFormatter, traceWriter, request); // copy non-overridable members from inner formatter _innerTracer.CopyNonOverriableMembersFromInner(this); MaxDepth = innerFormatter.MaxDepth; ReadBufferSize = innerFormatter.ReadBufferSize; }
public JsonMediaTypeFormatterTracer( JsonMediaTypeFormatter innerFormatter, ITraceWriter traceWriter, HttpRequestMessage request ) : base(innerFormatter) { _inner = innerFormatter; _innerTracer = new MediaTypeFormatterTracer(innerFormatter, traceWriter, request); }
public XmlMediaTypeFormatterTracer(XmlMediaTypeFormatter innerFormatter, ITraceWriter traceWriter, HttpRequestMessage request) { _innerTracer = new MediaTypeFormatterTracer(innerFormatter, traceWriter, request); // copy values we cannot override _innerTracer.CopyNonOverriableMembersFromInner(this); UseXmlSerializer = innerFormatter.UseXmlSerializer; Indent = innerFormatter.Indent; MaxDepth = innerFormatter.MaxDepth; }
public ContentNegotiationResult Negotiate( Type type, HttpRequestMessage request, IEnumerable <MediaTypeFormatter> formatters ) { ContentNegotiationResult result = null; _traceWriter.TraceBeginEnd( request, TraceCategories.FormattingCategory, TraceLevel.Info, _innerNegotiator.GetType().Name, NegotiateMethodName, beginTrace: (tr) => { tr.Message = Error.Format( SRResources.TraceNegotiateFormatter, type.Name, FormattingUtilities.FormattersToString(formatters) ); }, execute: () => { result = _innerNegotiator.Negotiate(type, request, formatters); }, endTrace: (tr) => { tr.Message = Error.Format( SRResources.TraceSelectedFormatter, result == null ? SRResources.TraceNoneObjectMessage : MediaTypeFormatterTracer .ActualMediaTypeFormatter(result.Formatter) .GetType().Name, result == null || result.MediaType == null ? SRResources.TraceNoneObjectMessage : result.MediaType.ToString() ); }, errorTrace: null ); if (result != null) { result.Formatter = MediaTypeFormatterTracer.CreateTracer( result.Formatter, _traceWriter, request ); } return(result); }
public JsonMediaTypeFormatterTracer(JsonMediaTypeFormatter innerFormatter, ITraceWriter traceWriter, HttpRequestMessage request) { _innerTracer = new MediaTypeFormatterTracer(innerFormatter, traceWriter, request); // copy values we cannot override _innerTracer.CopyNonOverriableMembersFromInner(this); MaxDepth = innerFormatter.MaxDepth; Indent = innerFormatter.Indent; UseDataContractJsonSerializer = innerFormatter.UseDataContractJsonSerializer; SerializerSettings = innerFormatter.SerializerSettings; }
private IEnumerable <MediaTypeFormatter> CreateFormatterTracers(HttpRequestMessage request, IEnumerable <MediaTypeFormatter> formatters) { List <MediaTypeFormatter> formatterTracers = new List <MediaTypeFormatter>(); foreach (MediaTypeFormatter formatter in formatters) { formatterTracers.Add(MediaTypeFormatterTracer.CreateTracer(formatter, _traceWriter, request)); } return(formatterTracers); }
public void Decorator_GetInner_On_All_MediaTypeFormatterTracers_Returns_Object_Of_Type_MediaTypeFormatter(MediaTypeFormatter formatter) { // Arrange HttpRequestMessage request = new HttpRequestMessage(); MediaTypeFormatter formatterTracer = MediaTypeFormatterTracer.CreateTracer(formatter, new TestTraceWriter(), request); // Act MediaTypeFormatter innerFormatter = Decorator.GetInner(formatterTracer); // Assert Assert.Same(formatter, innerFormatter); }
public void CreateTracer_Returns_Tracing_Formatter(MediaTypeFormatter formatter) { // Arrange HttpRequestMessage request = new HttpRequestMessage(); // Act MediaTypeFormatter tracingFormatter = MediaTypeFormatterTracer.CreateTracer(formatter, new TestTraceWriter(), request); // Assert IFormatterTracer tracer = Assert.IsAssignableFrom <IFormatterTracer>(tracingFormatter); Assert.Same(formatter, tracer.InnerFormatter); }
public void CreateTracer_Returns_Tracing_Formatter(Type formatterType) { // Arrange HttpRequestMessage request = new HttpRequestMessage(); MediaTypeFormatter formatter = (MediaTypeFormatter)Activator.CreateInstance(formatterType); // Act MediaTypeFormatter tracingFormatter = MediaTypeFormatterTracer.CreateTracer(formatter, new TestTraceWriter(), request); // Assert Assert.IsAssignableFrom <IFormatterTracer>(tracingFormatter); Assert.IsAssignableFrom(formatterType, tracingFormatter); }
public static MediaTypeFormatter CreateTracer(MediaTypeFormatter formatter, ITraceWriter traceWriter, HttpRequestMessage request) { // If we have been asked to wrap a tracer around a formatter, it could be // already wrapped, and there is nothing to do. But if we see it is a tracer // that is not associated with a request, we wrap it into a new tracer that // does have a request. The only formatter tracers without requests are the // ones in the default MediaTypeFormatterCollection in the HttpConfiguration. IFormatterTracer formatterTracer = formatter as IFormatterTracer; if (formatterTracer != null) { if (formatterTracer.Request == request) { return(formatter); } formatter = formatterTracer.InnerFormatter; } MediaTypeFormatter tracer = null; XmlMediaTypeFormatter xmlFormatter = formatter as XmlMediaTypeFormatter; JsonMediaTypeFormatter jsonFormatter = formatter as JsonMediaTypeFormatter; FormUrlEncodedMediaTypeFormatter formUrlFormatter = formatter as FormUrlEncodedMediaTypeFormatter; BufferedMediaTypeFormatter bufferedFormatter = formatter as BufferedMediaTypeFormatter; // We special-case Xml, Json and FormUrlEncoded formatters because we expect to be able // to find them with IsAssignableFrom in the MediaTypeFormatterCollection. if (xmlFormatter != null) { tracer = new XmlMediaTypeFormatterTracer(xmlFormatter, traceWriter, request); } else if (jsonFormatter != null) { tracer = new JsonMediaTypeFormatterTracer(jsonFormatter, traceWriter, request); } else if (formUrlFormatter != null) { tracer = new FormUrlEncodedMediaTypeFormatterTracer(formUrlFormatter, traceWriter, request); } else if (bufferedFormatter != null) { tracer = new BufferedMediaTypeFormatterTracer(bufferedFormatter, traceWriter, request); } else { tracer = new MediaTypeFormatterTracer(formatter, traceWriter, request); } return(tracer); }
public void CreateTracer_Loads_SupportedEncodings_From_InnerFormatter(Type formatterType) { // Arrange HttpRequestMessage request = new HttpRequestMessage(); MediaTypeFormatter formatter = (MediaTypeFormatter)Activator.CreateInstance(formatterType); Mock <Encoding> encoding = new Mock <Encoding>(); formatter.SupportedEncodings.Clear(); formatter.SupportedEncodings.Add(encoding.Object); // Act MediaTypeFormatter tracingFormatter = MediaTypeFormatterTracer.CreateTracer(formatter, new TestTraceWriter(), request); // Assert Assert.Equal(formatter.SupportedEncodings, tracingFormatter.SupportedEncodings); }
public void CreateTracer_Loads_RequiredMemberSelector_From_InnerFormatter(Type formatterType) { // Arrange HttpRequestMessage request = new HttpRequestMessage(); MediaTypeFormatter formatter = (MediaTypeFormatter)Activator.CreateInstance(formatterType); Mock <IRequiredMemberSelector> requiredMemberSelector = new Mock <IRequiredMemberSelector>(); formatter.RequiredMemberSelector = requiredMemberSelector.Object; // Act MediaTypeFormatter tracingFormatter = MediaTypeFormatterTracer.CreateTracer(formatter, new TestTraceWriter(), request); // Assert Assert.Equal(formatter.RequiredMemberSelector, tracingFormatter.RequiredMemberSelector); }
public void CreateTracer_Returns_Tracing_BufferedFormatter() { // Arrange HttpRequestMessage request = new HttpRequestMessage(); MediaTypeFormatter formatter = new Mock <BufferedMediaTypeFormatter>() { CallBase = true }.Object; // Act MediaTypeFormatter tracingFormatter = MediaTypeFormatterTracer.CreateTracer(formatter, new TestTraceWriter(), request); // Assert Assert.IsAssignableFrom <IFormatterTracer>(tracingFormatter); Assert.IsAssignableFrom <BufferedMediaTypeFormatter>(tracingFormatter); }
public void CreateTracer_Loads_MediaTypeMappings_From_InnerFormatter(Type formatterType) { // Arrange HttpRequestMessage request = new HttpRequestMessage(); MediaTypeFormatter formatter = (MediaTypeFormatter)Activator.CreateInstance(formatterType); Mock <MediaTypeMapping> mediaTypeMapping = new Mock <MediaTypeMapping>(new MediaTypeHeaderValue("application/dummy")); formatter.MediaTypeMappings.Clear(); formatter.MediaTypeMappings.Add(mediaTypeMapping.Object); // Act MediaTypeFormatter tracingFormatter = MediaTypeFormatterTracer.CreateTracer(formatter, new TestTraceWriter(), request); // Assert Assert.Equal(formatter.MediaTypeMappings, tracingFormatter.MediaTypeMappings); }
public void CreateTracer_Loads_SupportedMediaTypes_From_InnerFormatter(Type formatterType) { // Arrange HttpRequestMessage request = new HttpRequestMessage(); MediaTypeFormatter formatter = (MediaTypeFormatter)Activator.CreateInstance(formatterType); MediaTypeHeaderValue mediaTypeHeaderValue = new MediaTypeHeaderValue("application/dummy"); formatter.SupportedMediaTypes.Clear(); formatter.SupportedMediaTypes.Add(mediaTypeHeaderValue); // Act MediaTypeFormatter tracingFormatter = MediaTypeFormatterTracer.CreateTracer(formatter, new TestTraceWriter(), request); // Assert Assert.Equal(formatter.SupportedMediaTypes, tracingFormatter.SupportedMediaTypes); }
public void OnWriteToStreamAsync_Traces_And_Faults_When_Inner_Faults() { // Arrange InvalidOperationException exception = new InvalidOperationException("test"); Mock <MediaTypeFormatter> mockFormatter = new Mock <MediaTypeFormatter>() { CallBase = true }; TaskCompletionSource <object> tcs = new TaskCompletionSource <object>(); tcs.TrySetException(exception); mockFormatter.Setup( f => f.WriteToStreamAsync(It.IsAny <Type>(), It.IsAny <Object>(), It.IsAny <Stream>(), It.IsAny <HttpContentHeaders>(), It.IsAny <TransportContext>())). Returns(tcs.Task); TestTraceWriter traceWriter = new TestTraceWriter(); HttpRequestMessage request = new HttpRequestMessage(); request.Content = new StringContent(""); MediaTypeFormatterTracer tracer = new MediaTypeFormatterTracer(mockFormatter.Object, traceWriter, request); TraceRecord[] expectedTraces = new TraceRecord[] { new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "WriteToStreamAsync" }, new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Error) { Kind = TraceKind.End, Operation = "WriteToStreamAsync" } }; // Act Task task = tracer.WriteToStreamAsync(typeof(string), "sampleValue", new MemoryStream(), request.Content.Headers, transportContext: null); // Assert Exception thrown = Assert.Throws <InvalidOperationException>(() => task.Wait()); Assert.Equal <TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer()); Assert.Same(exception, thrown); Assert.Same(exception, traceWriter.Traces[1].Exception); }
public void OnReadFromStreamAsync_Traces_And_Throws_When_Inner_Throws() { // Arrange InvalidOperationException exception = new InvalidOperationException("test"); Mock <MediaTypeFormatter> mockFormatter = new Mock <MediaTypeFormatter>() { CallBase = true }; mockFormatter.Setup( f => f.ReadFromStreamAsync(It.IsAny <Type>(), It.IsAny <Stream>(), It.IsAny <HttpContentHeaders>(), It.IsAny <IFormatterLogger>())).Throws(exception); TestTraceWriter traceWriter = new TestTraceWriter(); HttpRequestMessage request = new HttpRequestMessage(); request.Content = new StringContent(""); MediaTypeFormatterTracer tracer = new MediaTypeFormatterTracer(mockFormatter.Object, traceWriter, request); TraceRecord[] expectedTraces = new TraceRecord[] { new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "ReadFromStreamAsync" }, new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Error) { Kind = TraceKind.End, Operation = "ReadFromStreamAsync" } }; // Act Exception thrown = Assert.Throws <InvalidOperationException>(() => tracer.ReadFromStreamAsync(typeof(string), new MemoryStream(), request.Content.Headers, null)); // Assert Assert.Equal <TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer()); Assert.Same(exception, thrown); Assert.Same(exception, traceWriter.Traces[1].Exception); }
public void OnReadFromStreamAsync_Traces() { // Arrange Mock <MediaTypeFormatter> mockFormatter = new Mock <MediaTypeFormatter>() { CallBase = true }; mockFormatter.Setup( f => f.ReadFromStreamAsync(It.IsAny <Type>(), It.IsAny <Stream>(), It.IsAny <HttpContentHeaders>(), It.IsAny <IFormatterLogger>())). Returns(TaskHelpers.FromResult <object>("sampleValue")); TestTraceWriter traceWriter = new TestTraceWriter(); HttpRequestMessage request = new HttpRequestMessage(); request.Content = new StringContent(""); MediaTypeFormatterTracer tracer = new MediaTypeFormatterTracer(mockFormatter.Object, traceWriter, request); TraceRecord[] expectedTraces = new TraceRecord[] { new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "ReadFromStreamAsync" }, new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Info) { Kind = TraceKind.End, Operation = "ReadFromStreamAsync" } }; // Act Task <object> task = tracer.ReadFromStreamAsync(typeof(string), new MemoryStream(), request.Content.Headers, null); string result = task.Result as string; // Assert Assert.Equal <TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer()); Assert.Equal("sampleValue", result); }
public void OnWriteToStreamAsync_Traces_And_Faults_When_Inner_Faults() { // Arrange InvalidOperationException exception = new InvalidOperationException("test"); Mock<MediaTypeFormatter> mockFormatter = new Mock<MediaTypeFormatter>() { CallBase = true }; TaskCompletionSource<object> tcs = new TaskCompletionSource<object>(); tcs.TrySetException(exception); mockFormatter.Setup( f => f.WriteToStreamAsync(It.IsAny<Type>(), It.IsAny<Object>(), It.IsAny<Stream>(), It.IsAny<HttpContentHeaders>(), It.IsAny<TransportContext>())). Returns(tcs.Task); TestTraceWriter traceWriter = new TestTraceWriter(); HttpRequestMessage request = new HttpRequestMessage(); request.Content = new StringContent(""); MediaTypeFormatterTracer tracer = new MediaTypeFormatterTracer(mockFormatter.Object, traceWriter, request); TraceRecord[] expectedTraces = new TraceRecord[] { new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "WriteToStreamAsync" }, new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Error) { Kind = TraceKind.End, Operation = "WriteToStreamAsync" } }; // Act Task task = tracer.WriteToStreamAsync(typeof(string), "sampleValue", new MemoryStream(), request.Content.Headers, transportContext: null); // Assert Exception thrown = Assert.Throws<InvalidOperationException>(() => task.Wait()); Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer()); Assert.Same(exception, thrown); Assert.Same(exception, traceWriter.Traces[1].Exception); }
public void GetPerRequestFormatterInstance_Returns_Tracing_MediaTypeFormatter() { // Arrange Mock<MediaTypeFormatter> mockReturnFormatter = new Mock<MediaTypeFormatter>() { CallBase = true }; Mock<MediaTypeFormatter> mockFormatter = new Mock<MediaTypeFormatter>() { CallBase = true }; mockFormatter.Setup( f => f.GetPerRequestFormatterInstance(It.IsAny<Type>(), It.IsAny<HttpRequestMessage>(), It.IsAny<MediaTypeHeaderValue>())).Returns(mockReturnFormatter.Object); TestTraceWriter traceWriter = new TestTraceWriter(); HttpRequestMessage request = new HttpRequestMessage(); MediaTypeFormatterTracer tracer = new MediaTypeFormatterTracer(mockFormatter.Object, traceWriter, request); // Act MediaTypeFormatter actualFormatter = tracer.GetPerRequestFormatterInstance(typeof(string), request, new MediaTypeHeaderValue("application/json")); // Assert Assert.IsAssignableFrom<IFormatterTracer>(actualFormatter); }
public async Task ReadFromStream_Traces() { // Arrange string contentType = "text/plain"; object value = new object(); CustomMediaTypeFormatter formatter = new CustomMediaTypeFormatter(value); formatter.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse(contentType)); TestTraceWriter traceWriter = new TestTraceWriter(); HttpRequestMessage request = new HttpRequestMessage(); request.Content = new StringContent("42", Encoding.Default, contentType); MediaTypeFormatterTracer tracer = new MediaTypeFormatterTracer(formatter, traceWriter, request); TraceRecord[] expectedTraces = new TraceRecord[] { new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "ReadFromStreamAsync" }, new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Info) { Kind = TraceKind.End, Operation = "ReadFromStreamAsync" } }; // Act object valueReturned = await request.Content.ReadAsAsync<object>(new[] { tracer }); // Assert Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer()); Assert.Equal(value, valueReturned); }
public static MediaTypeFormatter CreateTracer(MediaTypeFormatter formatter, ITraceWriter traceWriter, HttpRequestMessage request) { // If we have been asked to wrap a tracer around a formatter, it could be // already wrapped, and there is nothing to do. But if we see it is a tracer // that is not associated with a request, we wrap it into a new tracer that // does have a request. The only formatter tracers without requests are the // ones in the default MediaTypeFormatterCollection in the HttpConfiguration. IFormatterTracer formatterTracer = formatter as IFormatterTracer; if (formatterTracer != null) { if (formatterTracer.Request == request) { return formatter; } formatter = formatterTracer.InnerFormatter; } MediaTypeFormatter tracer = null; XmlMediaTypeFormatter xmlFormatter = formatter as XmlMediaTypeFormatter; JsonMediaTypeFormatter jsonFormatter = formatter as JsonMediaTypeFormatter; FormUrlEncodedMediaTypeFormatter formUrlFormatter = formatter as FormUrlEncodedMediaTypeFormatter; BufferedMediaTypeFormatter bufferedFormatter = formatter as BufferedMediaTypeFormatter; // We special-case Xml, Json and FormUrlEncoded formatters because we expect to be able // to find them with IsAssignableFrom in the MediaTypeFormatterCollection. if (xmlFormatter != null) { tracer = new XmlMediaTypeFormatterTracer(xmlFormatter, traceWriter, request); } else if (jsonFormatter != null) { tracer = new JsonMediaTypeFormatterTracer(jsonFormatter, traceWriter, request); } else if (formUrlFormatter != null) { tracer = new FormUrlEncodedMediaTypeFormatterTracer(formUrlFormatter, traceWriter, request); } else if (bufferedFormatter != null) { tracer = new BufferedMediaTypeFormatterTracer(bufferedFormatter, traceWriter, request); } else { tracer = new MediaTypeFormatterTracer(formatter, traceWriter, request); } return tracer; }
public async Task WriteToStream_Traces() { // Arrange object value = new object(); CustomMediaTypeFormatter formatter = new CustomMediaTypeFormatter(value); TestTraceWriter traceWriter = new TestTraceWriter(); HttpRequestMessage request = new HttpRequestMessage(); MediaTypeFormatterTracer tracer = new MediaTypeFormatterTracer(formatter, traceWriter, request); request.Content = new ObjectContent<object>(value, tracer); TraceRecord[] expectedTraces = new TraceRecord[] { new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "WriteToStreamAsync" }, new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Info) { Kind = TraceKind.End, Operation = "WriteToStreamAsync" } }; // Act await request.Content.CopyToAsync(new MemoryStream()); // Assert Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer()); }
public FormUrlEncodedMediaTypeFormatterTracer(MediaTypeFormatter innerFormatter, ITraceWriter traceWriter, HttpRequestMessage request) { _innerTracer = new MediaTypeFormatterTracer(innerFormatter, traceWriter, request); }
public XmlMediaTypeFormatterTracer(MediaTypeFormatter innerFormatter, ITraceWriter traceWriter, HttpRequestMessage request) { _innerTracer = new MediaTypeFormatterTracer(innerFormatter, traceWriter, request); }