Ejemplo n.º 1
0
        public void Authentication_UseMultiInterfaceStreamContent_Success()
        {
            RemoteInvoke(async useManagedHandlerString =>
            {
                string username           = "******";
                string password           = "******";
                Uri uri                   = Configuration.Http.BasicAuthUriForCreds(secure: false, userName: username, password: password);
                HttpClientHandler handler = CreateHttpClientHandler(useManagedHandlerString);
                handler.Credentials       = new NetworkCredential(username, password);

                using (var client = new HttpClient(handler))
                {
                    byte[] postData = Encoding.UTF8.GetBytes("This is data to post.");
                    var stream      = new MultiInterfaceReadOnlyStream(postData);
                    var content     = new MultiInterfaceStreamContent(stream);

                    using (HttpResponseMessage response = await client.PostAsync(uri, content))
                    {
                        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                        string responseContent = await response.Content.ReadAsStringAsync();
                    }
                }

                return(SuccessExitCode);
            }, UseManagedHandler.ToString()).Dispose();
        }
Ejemplo n.º 2
0
        public void Authentication_UseStreamContent_Throws()
        {
            RemoteInvoke(async useManagedHandlerString =>
            {
                // This test validates the current limitation of CoreFx's NetFxToWinRtStreamAdapter
                // which throws exceptions when trying to rewind a .NET Stream when it needs to be
                // re-POST'd to the server.
                string username           = "******";
                string password           = "******";
                Uri uri                   = Configuration.Http.BasicAuthUriForCreds(secure: false, userName: username, password: password);
                HttpClientHandler handler = CreateHttpClientHandler(useManagedHandlerString);
                handler.Credentials       = new NetworkCredential(username, password);

                using (var client = new HttpClient(handler))
                {
                    byte[] postData = Encoding.UTF8.GetBytes("This is data to post.");
                    var stream      = new MemoryStream(postData, false);
                    var content     = new StreamContent(stream);

                    await Assert.ThrowsAsync <HttpRequestException>(() => client.PostAsync(uri, content));
                }

                return(SuccessExitCode);
            }, UseManagedHandler.ToString()).Dispose();
        }
        public void Manual_SendClientCertificateWithNoEKUToRemoteServer_OK()
        {
            if (!CanTestClientCertificates) // can't use [Conditional*] right now as it's evaluated at the wrong time for the managed handler
            {
                _output.WriteLine($"Skipping {nameof(Manual_SendClientCertificateWithNoEKUToRemoteServer_OK)}()");
                return;
            }

            // UAP HTTP stack caches connections per-process. This causes interference when these tests run in
            // the same process as the other tests. Each test needs to be isolated to its own process.
            // See dicussion: https://github.com/dotnet/corefx/issues/21945
            RemoteInvoke(async useManagedHandlerString =>
            {
                var cert = Configuration.Certificates.GetNoEKUCertificate();
                HttpClientHandler handler = CreateHttpClientHandler(useManagedHandlerString);
                handler.ClientCertificates.Add(cert);
                using (var client = new HttpClient(handler))
                {
                    HttpResponseMessage response = await client.GetAsync(Configuration.Http.EchoClientCertificateRemoteServer);
                    Assert.Equal(HttpStatusCode.OK, response.StatusCode);

                    string body      = await response.Content.ReadAsStringAsync();
                    byte[] bytes     = Convert.FromBase64String(body);
                    var receivedCert = new X509Certificate2(bytes);
                    Assert.Equal(cert, receivedCert);

                    return(SuccessExitCode);
                }
            }, UseManagedHandler.ToString()).Dispose();
        }
        public void Manual_SendClientCertificateWithServerAuthEKUToRemoteServer_Forbidden()
        {
            if (UseManagedHandler)
            {
                // TODO #23128: The managed handler is currently sending out client certificates when it shouldn't.
                return;
            }

            if (!CanTestClientCertificates) // can't use [Conditional*] right now as it's evaluated at the wrong time for the managed handler
            {
                _output.WriteLine($"Skipping {nameof(Manual_SendClientCertificateWithServerAuthEKUToRemoteServer_Forbidden)}()");
                return;
            }

            // UAP HTTP stack caches connections per-process. This causes interference when these tests run in
            // the same process as the other tests. Each test needs to be isolated to its own process.
            // See dicussion: https://github.com/dotnet/corefx/issues/21945
            RemoteInvoke(async useManagedHandlerString =>
            {
                var cert = Configuration.Certificates.GetServerCertificate();
                HttpClientHandler handler = CreateHttpClientHandler(useManagedHandlerString);
                handler.ClientCertificates.Add(cert);
                using (var client = new HttpClient(handler))
                {
                    HttpResponseMessage response = await client.GetAsync(Configuration.Http.EchoClientCertificateRemoteServer);
                    Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);

                    return(SuccessExitCode);
                }
            }, UseManagedHandler.ToString()).Dispose();
        }
Ejemplo n.º 5
0
        public async Task UseCallback_BadCertificate_ExpectedPolicyErrors(string url, SslPolicyErrors expectedErrors)
        {
            if (!BackendSupportsCustomCertificateHandlingAndClientSupportsDHECipherSuites)
            {
                return;
            }

            if (PlatformDetection.IsUap)
            {
                // UAP HTTP stack caches connections per-process. This causes interference when these tests run in
                // the same process as the other tests. Each test needs to be isolated to its own process.
                // See dicussion: https://github.com/dotnet/corefx/issues/21945
                RemoteInvoke((remoteUrl, remoteExpectedErrors, useManagedHandlerString) =>
                {
                    UseCallback_BadCertificate_ExpectedPolicyErrors_Helper(
                        remoteUrl,
                        bool.Parse(useManagedHandlerString),
                        (SslPolicyErrors)Enum.Parse(typeof(SslPolicyErrors), remoteExpectedErrors)).Wait();

                    return(SuccessExitCode);
                }, url, expectedErrors.ToString(), UseManagedHandler.ToString()).Dispose();
            }
            else
            {
                await UseCallback_BadCertificate_ExpectedPolicyErrors_Helper(url, UseManagedHandler, expectedErrors);
            }
        }
        public void ProxySetViaEnvironmentVariable_DefaultProxyCredentialsUsed(bool useProxy)
        {
            bool envVarsSupported = UseManagedHandler || !RuntimeInformation.IsOSPlatform(OSPlatform.Windows);

            if (!envVarsSupported)
            {
                return;
            }

            int port = 0;
            Task <LoopbackGetRequestHttpProxy.ProxyResult> proxyTask = null;

            if (useProxy)
            {
                proxyTask = LoopbackGetRequestHttpProxy.StartAsync(out port, requireAuth: true, expectCreds: true);
            }

            const string ExpectedUsername = "******";
            const string ExpectedPassword = "******";

            // libcurl will read a default proxy from the http_proxy environment variable.  Ensure that when it does,
            // our default proxy credentials are used.  To avoid messing up anything else in this process, we run the
            // test in another process.
            var psi = new ProcessStartInfo();

            psi.Environment.Add("http_proxy", $"http://localhost:{port}");
            RemoteInvoke((useProxyString, useManagedHandlerString) =>
            {
                using (HttpClientHandler handler = CreateHttpClientHandler(useManagedHandlerString))
                    using (var client = new HttpClient(handler))
                    {
                        var creds = new NetworkCredential(ExpectedUsername, ExpectedPassword);
                        handler.DefaultProxyCredentials = creds;
                        handler.UseProxy = bool.Parse(useProxyString);

                        Task <HttpResponseMessage> responseTask = client.GetAsync(Configuration.Http.RemoteEchoServer);
                        Task <string> responseStringTask        = responseTask.ContinueWith(t =>
                        {
                            using (t.Result) return(t.Result.Content.ReadAsStringAsync());
                        }, TaskScheduler.Default).Unwrap();
                        Task.WaitAll(responseTask, responseStringTask);

                        TestHelper.VerifyResponseBody(responseStringTask.Result, responseTask.Result.Content.Headers.ContentMD5, false, null);
                    }
                return(SuccessExitCode);
            }, useProxy.ToString(), UseManagedHandler.ToString(), new RemoteInvokeOptions {
                StartInfo = psi
            }).Dispose();

            if (useProxy)
            {
                Assert.Equal($"{ExpectedUsername}:{ExpectedPassword}", proxyTask.Result.AuthenticationHeaderValue);
            }
        }
Ejemplo n.º 7
0
        public void SendAsync_ExpectedDiagnosticSourceNoLogging()
        {
            RemoteInvoke(useManagedHandlerString =>
            {
                bool requestLogged       = false;
                bool responseLogged      = false;
                bool activityStartLogged = false;
                bool activityStopLogged  = false;

                var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
                {
                    if (kvp.Key.Equals("System.Net.Http.Request"))
                    {
                        requestLogged = true;
                    }
                    else if (kvp.Key.Equals("System.Net.Http.Response"))
                    {
                        responseLogged = true;
                    }
                    else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Start"))
                    {
                        activityStartLogged = true;
                    }
                    else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop"))
                    {
                        activityStopLogged = true;
                    }
                });

                using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
                {
                    using (HttpClient client = CreateHttpClient(useManagedHandlerString))
                    {
                        LoopbackServer.CreateServerAsync(async(server, url) =>
                        {
                            Task <List <string> > requestLines = LoopbackServer.AcceptSocketAsync(server,
                                                                                                  (s, stream, reader, writer) => LoopbackServer.ReadWriteAcceptedAsync(s, reader, writer));
                            Task <HttpResponseMessage> response = client.GetAsync(url);
                            await Task.WhenAll(response, requestLines);

                            AssertNoHeadersAreInjected(requestLines.Result);
                            response.Result.Dispose();
                        }).Wait();
                    }

                    Assert.False(requestLogged, "Request was logged while logging disabled.");
                    Assert.False(activityStartLogged, "HttpRequestOut.Start was logged while logging disabled.");
                    WaitForFalse(() => responseLogged, TimeSpan.FromSeconds(1), "Response was logged while logging disabled.");
                    Assert.False(activityStopLogged, "HttpRequestOut.Stop was logged while logging disabled.");
                }
                return(SuccessExitCode);
            }, UseManagedHandler.ToString()).Dispose();
        }
Ejemplo n.º 8
0
        public void SendAsync_ExpectedDiagnosticSourceNewAndDeprecatedEventsLogging()
        {
            RemoteInvoke(useManagedHandlerString =>
            {
                bool requestLogged       = false;
                bool responseLogged      = false;
                bool activityStartLogged = false;
                bool activityStopLogged  = false;

                var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
                {
                    if (kvp.Key.Equals("System.Net.Http.Request"))
                    {
                        requestLogged = true;
                    }
                    else if (kvp.Key.Equals("System.Net.Http.Response"))
                    {
                        responseLogged = true;
                    }
                    else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Start"))
                    {
                        activityStartLogged = true;
                    }
                    else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop"))
                    {
                        activityStopLogged = true;
                    }
                });

                using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
                {
                    diagnosticListenerObserver.Enable();
                    using (HttpClient client = CreateHttpClient(useManagedHandlerString))
                    {
                        client.GetAsync(Configuration.Http.RemoteEchoServer).Result.Dispose();
                    }

                    Assert.True(activityStartLogged, "HttpRequestOut.Start was not logged.");
                    Assert.True(requestLogged, "Request was not logged.");
                    // Poll with a timeout since logging response is not synchronized with returning a response.
                    WaitForTrue(() => activityStopLogged, TimeSpan.FromSeconds(1), "HttpRequestOut.Stop was not logged within 1 second timeout.");
                    Assert.True(responseLogged, "Response was not logged.");
                    diagnosticListenerObserver.Disable();
                }

                return(SuccessExitCode);
            }, UseManagedHandler.ToString()).Dispose();
        }
Ejemplo n.º 9
0
        public void SendAsync_ExpectedDiagnosticSourceUrlFilteredActivityLogging()
        {
            RemoteInvoke(useManagedHandlerString =>
            {
                bool activityStartLogged = false;
                bool activityStopLogged  = false;

                var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
                {
                    if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Start"))
                    {
                        activityStartLogged = true;
                    }
                    else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop"))
                    {
                        activityStopLogged = true;
                    }
                });

                using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
                {
                    diagnosticListenerObserver.Enable((s, r, _) =>
                    {
                        if (s.StartsWith("System.Net.Http.HttpRequestOut"))
                        {
                            var request = r as HttpRequestMessage;
                            if (request != null)
                            {
                                return(!request.RequestUri.Equals(Configuration.Http.RemoteEchoServer));
                            }
                        }
                        return(true);
                    });
                    using (HttpClient client = CreateHttpClient(useManagedHandlerString))
                    {
                        client.GetAsync(Configuration.Http.RemoteEchoServer).Result.Dispose();
                    }
                    Assert.False(activityStartLogged, "HttpRequestOut.Start was logged while URL disabled.");
                    // Poll with a timeout since logging response is not synchronized with returning a response.
                    Assert.False(activityStopLogged, "HttpRequestOut.Stop was logged while URL disabled.");
                    diagnosticListenerObserver.Disable();
                }

                return(SuccessExitCode);
            }, UseManagedHandler.ToString()).Dispose();
        }
Ejemplo n.º 10
0
        public void SendAsync_ExpectedDiagnosticCancelledActivityLogging()
        {
            RemoteInvoke(useManagedHandlerString =>
            {
                bool cancelLogged = false;
                var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
                {
                    if (kvp.Key == "System.Net.Http.HttpRequestOut.Stop")
                    {
                        Assert.NotNull(kvp.Value);
                        GetPropertyValueFromAnonymousTypeInstance <HttpRequestMessage>(kvp.Value, "Request");
                        var status = GetPropertyValueFromAnonymousTypeInstance <TaskStatus>(kvp.Value, "RequestTaskStatus");
                        Assert.Equal(TaskStatus.Canceled, status);
                        Volatile.Write(ref cancelLogged, true);
                    }
                });

                using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
                {
                    diagnosticListenerObserver.Enable();
                    using (HttpClient client = CreateHttpClient(useManagedHandlerString))
                    {
                        LoopbackServer.CreateServerAsync(async(server, url) =>
                        {
                            CancellationTokenSource tcs = new CancellationTokenSource();
                            Task request = LoopbackServer.AcceptSocketAsync(server,
                                                                            (s, stream, reader, writer) =>
                            {
                                tcs.Cancel();
                                return(LoopbackServer.ReadWriteAcceptedAsync(s, reader, writer));
                            });
                            Task response = client.GetAsync(url, tcs.Token);
                            await Assert.ThrowsAnyAsync <Exception>(() => TestHelper.WhenAllCompletedOrAnyFailed(response, request));
                        }).Wait();
                    }
                }
                // Poll with a timeout since logging response is not synchronized with returning a response.
                WaitForTrue(() => Volatile.Read(ref cancelLogged), TimeSpan.FromSeconds(1),
                            "Cancellation was not logged within 1 second timeout.");
                diagnosticListenerObserver.Disable();

                return(SuccessExitCode);
            }, UseManagedHandler.ToString()).Dispose();
        }
Ejemplo n.º 11
0
        public void SendAsync_ExpectedDiagnosticExceptionActivityLogging()
        {
            RemoteInvoke(useManagedHandlerString =>
            {
                bool exceptionLogged           = false;
                bool activityStopLogged        = false;
                var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
                {
                    if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop"))
                    {
                        Assert.NotNull(kvp.Value);
                        GetPropertyValueFromAnonymousTypeInstance <HttpRequestMessage>(kvp.Value, "Request");
                        var requestStatus = GetPropertyValueFromAnonymousTypeInstance <TaskStatus>(kvp.Value, "RequestTaskStatus");
                        Assert.Equal(TaskStatus.Faulted, requestStatus);

                        activityStopLogged = true;
                    }
                    else if (kvp.Key.Equals("System.Net.Http.Exception"))
                    {
                        Assert.NotNull(kvp.Value);
                        GetPropertyValueFromAnonymousTypeInstance <Exception>(kvp.Value, "Exception");

                        exceptionLogged = true;
                    }
                });

                using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
                {
                    diagnosticListenerObserver.Enable();
                    using (HttpClient client = CreateHttpClient(useManagedHandlerString))
                    {
                        Assert.ThrowsAsync <HttpRequestException>(() => client.GetAsync($"http://{Guid.NewGuid()}.com")).Wait();
                    }
                    // Poll with a timeout since logging response is not synchronized with returning a response.
                    WaitForTrue(() => activityStopLogged, TimeSpan.FromSeconds(1),
                                "Response with exception was not logged within 1 second timeout.");
                    Assert.True(exceptionLogged, "Exception was not logged");
                    diagnosticListenerObserver.Disable();
                }

                return(SuccessExitCode);
            }, UseManagedHandler.ToString()).Dispose();
        }
Ejemplo n.º 12
0
        public void SendAsync_HttpTracingEnabled_Succeeds()
        {
            RemoteInvoke(async useManagedHandlerString =>
            {
                using (var listener = new TestEventListener("Microsoft-System-Net-Http", EventLevel.Verbose))
                {
                    var events = new ConcurrentQueue <EventWrittenEventArgs>();
                    await listener.RunWithCallbackAsync(events.Enqueue, async() =>
                    {
                        // Exercise various code paths to get coverage of tracing
                        using (HttpClient client = CreateHttpClient(useManagedHandlerString))
                        {
                            // Do a get to a loopback server
                            await LoopbackServer.CreateServerAsync(async(server, url) =>
                            {
                                await TestHelper.WhenAllCompletedOrAnyFailed(
                                    LoopbackServer.ReadRequestAndSendResponseAsync(server),
                                    client.GetAsync(url));
                            });

                            // Do a post to a remote server
                            byte[] expectedData        = Enumerable.Range(0, 20000).Select(i => unchecked ((byte)i)).ToArray();
                            HttpContent content        = new ByteArrayContent(expectedData);
                            content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(expectedData);
                            using (HttpResponseMessage response = await client.PostAsync(Configuration.Http.RemoteEchoServer, content))
                            {
                                Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                            }
                        }
                    });

                    // We don't validate receiving specific events, but rather that we do at least
                    // receive some events, and that enabling tracing doesn't cause other failures
                    // in processing.
                    Assert.DoesNotContain(events, ev => ev.EventId == 0); // make sure there are no event source error messages
                    Assert.InRange(events.Count, 1, int.MaxValue);
                }

                return(SuccessExitCode);
            }, UseManagedHandler.ToString()).Dispose();
        }
Ejemplo n.º 13
0
        public void Authentication_UseMultiInterfaceNonRewindableStreamContent_Throws()
        {
            RemoteInvoke(async useManagedHandlerString =>
            {
                string username           = "******";
                string password           = "******";
                Uri uri                   = Configuration.Http.BasicAuthUriForCreds(secure: false, userName: username, password: password);
                HttpClientHandler handler = CreateHttpClientHandler(useManagedHandlerString);
                handler.Credentials       = new NetworkCredential(username, password);

                using (var client = new HttpClient(handler))
                {
                    byte[] postData = Encoding.UTF8.GetBytes("This is data to post.");
                    var stream      = new MultiInterfaceNonRewindableReadOnlyStream(postData);
                    var content     = new MultiInterfaceStreamContent(stream);

                    await Assert.ThrowsAsync <HttpRequestException>(() => client.PostAsync(uri, content));
                }

                return(SuccessExitCode);
            }, UseManagedHandler.ToString()).Dispose();
        }
Ejemplo n.º 14
0
        public async Task UseCallback_BadCertificate_ExpectedPolicyErrors(string url, SslPolicyErrors expectedErrors)
        {
            const int SEC_E_BUFFER_TOO_SMALL = unchecked ((int)0x80090321);

            if (!BackendSupportsCustomCertificateHandlingAndClientSupportsDHECipherSuites)
            {
                return;
            }

            try
            {
                if (PlatformDetection.IsUap)
                {
                    // UAP HTTP stack caches connections per-process. This causes interference when these tests run in
                    // the same process as the other tests. Each test needs to be isolated to its own process.
                    // See dicussion: https://github.com/dotnet/corefx/issues/21945
                    RemoteInvoke((remoteUrl, remoteExpectedErrors, useManagedHandlerString) =>
                    {
                        UseCallback_BadCertificate_ExpectedPolicyErrors_Helper(
                            remoteUrl,
                            bool.Parse(useManagedHandlerString),
                            (SslPolicyErrors)Enum.Parse(typeof(SslPolicyErrors), remoteExpectedErrors)).Wait();

                        return(SuccessExitCode);
                    }, url, expectedErrors.ToString(), UseManagedHandler.ToString()).Dispose();
                }
                else
                {
                    await UseCallback_BadCertificate_ExpectedPolicyErrors_Helper(url, UseManagedHandler, expectedErrors);
                }
            }
            catch (HttpRequestException e) when(e.InnerException?.GetType().Name == "WinHttpException" &&
                                                e.InnerException.HResult == SEC_E_BUFFER_TOO_SMALL &&
                                                !PlatformDetection.IsWindows10Version1607OrGreater)
            {
                // Testing on old Windows versions can hit https://github.com/dotnet/corefx/issues/7812
                // Ignore SEC_E_BUFFER_TOO_SMALL error on such cases.
            }
        }
Ejemplo n.º 15
0
        public void SendAsync_ExpectedDiagnosticSourceLogging()
        {
            RemoteInvoke(useManagedHandlerString =>
            {
                bool requestLogged   = false;
                Guid requestGuid     = Guid.Empty;
                bool responseLogged  = false;
                Guid responseGuid    = Guid.Empty;
                bool exceptionLogged = false;
                bool activityLogged  = false;

                var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
                {
                    if (kvp.Key.Equals("System.Net.Http.Request"))
                    {
                        Assert.NotNull(kvp.Value);
                        GetPropertyValueFromAnonymousTypeInstance <HttpRequestMessage>(kvp.Value, "Request");
                        requestGuid   = GetPropertyValueFromAnonymousTypeInstance <Guid>(kvp.Value, "LoggingRequestId");
                        requestLogged = true;
                    }
                    else if (kvp.Key.Equals("System.Net.Http.Response"))
                    {
                        Assert.NotNull(kvp.Value);

                        GetPropertyValueFromAnonymousTypeInstance <HttpResponseMessage>(kvp.Value, "Response");
                        responseGuid      = GetPropertyValueFromAnonymousTypeInstance <Guid>(kvp.Value, "LoggingRequestId");
                        var requestStatus = GetPropertyValueFromAnonymousTypeInstance <TaskStatus>(kvp.Value, "RequestTaskStatus");
                        Assert.Equal(TaskStatus.RanToCompletion, requestStatus);

                        responseLogged = true;
                    }
                    else if (kvp.Key.Equals("System.Net.Http.Exception"))
                    {
                        exceptionLogged = true;
                    }
                    else if (kvp.Key.StartsWith("System.Net.Http.HttpRequestOut"))
                    {
                        activityLogged = true;
                    }
                });

                using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
                {
                    diagnosticListenerObserver.Enable(s => !s.Contains("HttpRequestOut"));
                    using (HttpClient client = CreateHttpClient(useManagedHandlerString))
                    {
                        client.GetAsync(Configuration.Http.RemoteEchoServer).Result.Dispose();
                    }

                    Assert.True(requestLogged, "Request was not logged.");
                    // Poll with a timeout since logging response is not synchronized with returning a response.
                    WaitForTrue(() => responseLogged, TimeSpan.FromSeconds(1), "Response was not logged within 1 second timeout.");
                    Assert.Equal(requestGuid, responseGuid);
                    Assert.False(exceptionLogged, "Exception was logged for successful request");
                    Assert.False(activityLogged, "HttpOutReq was logged while HttpOutReq logging was disabled");
                    diagnosticListenerObserver.Disable();
                }

                return(SuccessExitCode);
            }, UseManagedHandler.ToString()).Dispose();
        }
Ejemplo n.º 16
0
        public void SendAsync_ExpectedDiagnosticSourceActivityLogging()
        {
            RemoteInvoke(useManagedHandlerString =>
            {
                bool requestLogged       = false;
                bool responseLogged      = false;
                bool activityStartLogged = false;
                bool activityStopLogged  = false;
                bool exceptionLogged     = false;

                Activity parentActivity = new Activity("parent");
                parentActivity.AddBaggage("correlationId", Guid.NewGuid().ToString());
                parentActivity.AddBaggage("moreBaggage", Guid.NewGuid().ToString());
                parentActivity.AddTag("tag", "tag"); //add tag to ensure it is not injected into request
                parentActivity.Start();

                var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
                {
                    if (kvp.Key.Equals("System.Net.Http.Request"))
                    {
                        requestLogged = true;
                    }
                    else if (kvp.Key.Equals("System.Net.Http.Response"))
                    {
                        responseLogged = true;
                    }
                    else if (kvp.Key.Equals("System.Net.Http.Exception"))
                    {
                        exceptionLogged = true;
                    }
                    else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Start"))
                    {
                        Assert.NotNull(kvp.Value);
                        Assert.NotNull(Activity.Current);
                        Assert.Equal(parentActivity, Activity.Current.Parent);
                        GetPropertyValueFromAnonymousTypeInstance <HttpRequestMessage>(kvp.Value, "Request");

                        activityStartLogged = true;
                    }
                    else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop"))
                    {
                        Assert.NotNull(kvp.Value);
                        Assert.NotNull(Activity.Current);
                        Assert.Equal(parentActivity, Activity.Current.Parent);
                        Assert.True(Activity.Current.Duration != TimeSpan.Zero);
                        GetPropertyValueFromAnonymousTypeInstance <HttpRequestMessage>(kvp.Value, "Request");
                        GetPropertyValueFromAnonymousTypeInstance <HttpResponseMessage>(kvp.Value, "Response");
                        var requestStatus = GetPropertyValueFromAnonymousTypeInstance <TaskStatus>(kvp.Value, "RequestTaskStatus");
                        Assert.Equal(TaskStatus.RanToCompletion, requestStatus);

                        activityStopLogged = true;
                    }
                });

                using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
                {
                    diagnosticListenerObserver.Enable(s => s.Contains("HttpRequestOut"));
                    using (HttpClient client = CreateHttpClient(useManagedHandlerString))
                    {
                        LoopbackServer.CreateServerAsync(async(server, url) =>
                        {
                            Task <List <string> > requestLines = LoopbackServer.AcceptSocketAsync(server,
                                                                                                  (s, stream, reader, writer) => LoopbackServer.ReadWriteAcceptedAsync(s, reader, writer));
                            Task <HttpResponseMessage> response = client.GetAsync(url);
                            await Task.WhenAll(response, requestLines);

                            AssertHeadersAreInjected(requestLines.Result, parentActivity);
                            response.Result.Dispose();
                        }).Wait();
                    }

                    Assert.True(activityStartLogged, "HttpRequestOut.Start was not logged.");
                    Assert.False(requestLogged, "Request was logged when Activity logging was enabled.");
                    // Poll with a timeout since logging response is not synchronized with returning a response.
                    WaitForTrue(() => activityStopLogged, TimeSpan.FromSeconds(1), "HttpRequestOut.Stop was not logged within 1 second timeout.");
                    Assert.False(exceptionLogged, "Exception was logged for successful request");
                    Assert.False(responseLogged, "Response was logged when Activity logging was enabled.");
                    diagnosticListenerObserver.Disable();
                }

                return(SuccessExitCode);
            }, UseManagedHandler.ToString()).Dispose();
        }