コード例 #1
0
        public void SetupBlockPerfTest()
        {
            IgnoreIfNotLinkAll();

            // If you ran this test locally and it failed, run it again. If it fails multiple times, file a bug.
            TestRuntime.IgnoreInCI("This test randomly fails, so ignore it when doing CI (https://github.com/xamarin/maccore/issues/649)");

            const int iterations = 5000;

            // Set the XAMARIN_IOS_SKIP_BLOCK_CHECK environment variable to skip a few expensive validation checks done in the simulator
            var skipBlockCheck = Environment.GetEnvironmentVariable("XAMARIN_IOS_SKIP_BLOCK_CHECK");

            try {
                Environment.SetEnvironmentVariable("XAMARIN_IOS_SKIP_BLOCK_CHECK", "1");
                var unoptimizedCounter = 0;
                var unoptimizedAction  = new Action(() => unoptimizedCounter++);

                var optimizedCounter = 0;
                var optimizedAction  = new Action(() => optimizedCounter++);

                // Warm up
                SetupBlockOptimized(optimizedAction);
                SetupBlockUnoptimized(unoptimizedAction);

                // Run unoptimized
                var unoptimizedWatch = System.Diagnostics.Stopwatch.StartNew();
                unoptimizedCounter = 0;
                for (var i = 0; i < iterations; i++)
                {
                    SetupBlockUnoptimized(unoptimizedAction);
                }
                unoptimizedWatch.Stop();
                Assert.AreEqual(iterations, unoptimizedCounter, "Unoptimized Counter");

                // Run optimized
                var optimizedWatch = System.Diagnostics.Stopwatch.StartNew();
                optimizedCounter = 0;
                for (var i = 0; i < iterations; i++)
                {
                    SetupBlockOptimized(optimizedAction);
                }
                optimizedWatch.Stop();
                Assert.AreEqual(iterations, optimizedCounter, "Optimized Counter");

                //Console.WriteLine ("Optimized: {0} ms", optimizedWatch.ElapsedMilliseconds);
                //Console.WriteLine ("Unoptimized: {0} ms", unoptimizedWatch.ElapsedMilliseconds);
                //Console.WriteLine ("Speedup: {0}x", unoptimizedWatch.ElapsedTicks / (double) optimizedWatch.ElapsedTicks);
                // My testing found a 12-16x speedup on device and a 15-20x speedup in the simulator/desktop.
                // Setting to 6 to have a margin for random stuff happening, but this may still have to be adjusted.
#if NET && __TVOS__
                // Our optimization is correct, but the test case runs into https://github.com/dotnet/runtime/issues/58939 which overpowers most of our optimization gains.
                var speedup = 1.2;                 // Seems to be around 1.4/1.5, so let's see if 1.2 is consistently passing.
#else
                var speedup = 6;
#endif
                Assert.That(unoptimizedWatch.ElapsedTicks / (double)optimizedWatch.ElapsedTicks, Is.GreaterThan(speedup), $"At least {speedup}x speedup");
            } finally {
                Environment.SetEnvironmentVariable("XAMARIN_IOS_SKIP_BLOCK_CHECK", skipBlockCheck);
            }
        }
コード例 #2
0
        public void TestPACParsingUrlAsyncNoProxy()
        {
            TestRuntime.IgnoreInCI("CI bots might have proxies setup and will mean that the test will fail when trying to assert they are empty.");
            CFProxy [] proxies   = null;
            NSError    error     = null;
            NSObject   cbClient  = null;
            bool       done      = false;
            string     pacPath   = Path.Combine(NSBundle.MainBundle.BundlePath, "example.pac");
            var        pacUri    = new Uri(pacPath);
            var        targetUri = new Uri("http://docs.google.com");

            Exception ex;
            bool      foundProxies;

            // similar to the other tests, but we want to ensure that the async/await API works
            TestRuntime.RunAsync(DateTime.Now.AddSeconds(30), async() => {
                try {
                    CancellationTokenSource cancelSource = new CancellationTokenSource();
                    CancellationToken cancelToken        = cancelSource.Token;
                    var result = await CFNetwork.ExecuteProxyAutoConfigurationUrlAsync(pacUri, targetUri, cancelToken);
                    proxies    = result.proxies;
                    error      = result.error;
                } catch (Exception e) {
                    ex = e;
                } finally {
                    done = true;
                }
            }, () => done);
            Assert.IsNull(cbClient, "Null client");
            Assert.IsNull(error, "Null error");
            Assert.IsNotNull(proxies, "Not null proxies");
            Assert.AreEqual(1, proxies.Length, "Proxies length");
            Assert.AreEqual(CFProxyType.None, proxies [0].ProxyType);
        }
コード例 #3
0
        public void TestNSUrlSessionHandlerCookies()
        {
            var                  managedCookieResult = false;
            var                  nativeCookieResult  = false;
            Exception            ex             = null;
            var                  completed      = false;
            IEnumerable <string> nativeCookies  = null;
            IEnumerable <string> managedCookies = null;

            TestRuntime.RunAsync(DateTime.Now.AddSeconds(30), async() =>
            {
                var url = NetworkResources.Httpbin.GetSetCookieUrl("cookie", "chocolate-chip");
                try {
                    var managedHandler = new HttpClientHandler()
                    {
                        AllowAutoRedirect = false,
                    };
                    var managedClient   = new HttpClient(managedHandler);
                    var managedResponse = await managedClient.GetAsync(url);
                    managedCookieResult = managedResponse.Headers.TryGetValues("Set-Cookie", out managedCookies);

                    var nativeHandler = new NSUrlSessionHandler()
                    {
                        AllowAutoRedirect = false,
                    };
                    nativeHandler.AllowAutoRedirect = true;
                    var nativeClient   = new HttpClient(nativeHandler);
                    var nativeResponse = await nativeClient.GetAsync(url);
                    nativeCookieResult = nativeResponse.Headers.TryGetValues("Set-Cookie", out nativeCookies);
                } catch (Exception e) {
                    ex = e;
                } finally {
                    completed = true;
                }
            }, () => completed);

            if (!completed)
            {
                TestRuntime.IgnoreInCI("Transient network failure - ignore in CI");
            }
            Assert.IsTrue(completed, "Network request completed");
            Assert.IsNull(ex, "Exception");
            Assert.IsTrue(managedCookieResult, $"Failed to get managed cookies");
            Assert.IsTrue(nativeCookieResult, $"Failed to get native cookies");
            Assert.AreEqual(1, managedCookies.Count(), $"Managed Cookie Count");
            Assert.AreEqual(1, nativeCookies.Count(), $"Native Cookie Count");
            Assert.That(nativeCookies.First(), Does.StartWith("cookie=chocolate-chip;"), $"Native Cookie Value");
            Assert.That(managedCookies.First(), Does.StartWith("cookie=chocolate-chip;"), $"Managed Cookie Value");
        }
コード例 #4
0
        public void TestNSUrlSessionDefaultDisableCookiesWithManagedContainer()
        {
            // simple test. send a request with a set-cookie url, get the data
            // and ensure that the second request does not send any cookies.
            var url = NetworkResources.Httpbin.GetSetCookieUrl("cookie", "chocolate-chip");

            string nativeSetCookieResult = null;
            string nativeCookieResult    = null;
            var    cookieContainer       = new CookieContainer();


            Exception ex        = null;
            var       completed = false;

            TestRuntime.RunAsync(DateTime.Now.AddSeconds(30), async() => {
                try {
                    var nativeHandler = new NSUrlSessionHandler()
                    {
                        AllowAutoRedirect = true,
                        UseCookies        = false,
                    };
                    var nativeClient      = new HttpClient(nativeHandler);
                    var nativeResponse    = await nativeClient.GetAsync(url);
                    nativeSetCookieResult = await nativeResponse.Content.ReadAsStringAsync();

                    // got the response, preform a second queries to the cookies endpoint to get
                    // the actual cookies sent from the storage
                    nativeResponse     = await nativeClient.GetAsync(NetworkResources.Httpbin.CookiesUrl);
                    nativeCookieResult = await nativeResponse.Content.ReadAsStringAsync();
                } catch (Exception e) {
                    ex = e;
                } finally {
                    completed = true;
                }
            }, () => completed);

            if (!completed)
            {
                TestRuntime.IgnoreInCI("Transient network failure - ignore in CI");
            }
            Assert.IsTrue(completed, "Network request completed");
            Assert.IsNull(ex, "Exception");
            Assert.IsNotNull(nativeSetCookieResult, "Native set-cookies result");
            Assert.IsNotNull(nativeCookieResult, "Native cookies result");
            Assert.IsFalse(nativeCookieResult.Contains("chocolate-chip"));
            var cookiesFromServer = cookieContainer.GetCookies(new Uri(url));

            Assert.AreEqual(0, cookiesFromServer.Count, "Cookies received from server.");
        }
コード例 #5
0
        public void TestNSUrlSessionHandlerCookieContainer()
        {
            var url             = NetworkResources.Httpbin.CookiesUrl;
            var cookie          = new Cookie("cookie", "chocolate-chip");
            var cookieContainer = new CookieContainer();

            cookieContainer.Add(new Uri(url), cookie);

            string    managedCookieResult = null;
            string    nativeCookieResult  = null;
            Exception ex        = null;
            var       completed = false;

            TestRuntime.RunAsync(DateTime.Now.AddSeconds(30), async() => {
                try {
                    var managedHandler = new HttpClientHandler()
                    {
                        AllowAutoRedirect = false,
                        CookieContainer   = cookieContainer,
                    };
                    var managedClient   = new HttpClient(managedHandler);
                    var managedResponse = await managedClient.GetAsync(url);
                    managedCookieResult = await managedResponse.Content.ReadAsStringAsync();

                    var nativeHandler = new NSUrlSessionHandler()
                    {
                        AllowAutoRedirect = true,
                        CookieContainer   = cookieContainer,
                    };
                    var nativeClient   = new HttpClient(nativeHandler);
                    var nativeResponse = await nativeClient.GetAsync(url);
                    nativeCookieResult = await nativeResponse.Content.ReadAsStringAsync();
                } catch (Exception e) {
                    ex = e;
                } finally {
                    completed = true;
                }
            }, () => completed);

            if (!completed || managedCookieResult.Contains("502 Bad Gateway") || nativeCookieResult.Contains("502 Bad Gateway"))
            {
                TestRuntime.IgnoreInCI("Transient network failure - ignore in CI");
            }
            Assert.IsTrue(completed, "Network request completed");
            Assert.IsNull(ex, "Exception");
            Assert.IsNotNull(managedCookieResult, "Managed cookies result");
            Assert.IsNotNull(nativeCookieResult, "Native cookies result");
            Assert.AreEqual(managedCookieResult, nativeCookieResult, "Cookies");
        }
コード例 #6
0
        public void GHIssue8342(HttpStatusCode expectedStatus, string validUsername, string validPassword, string username, string password)
        {
            // create a http client to use with some creds that we do know are not valid
            var handler = new NSUrlSessionHandler()
            {
                Credentials = new NetworkCredential(username, password, "")
            };

            var client = new HttpClient(handler);

            bool           done       = false;
            HttpStatusCode httpStatus = HttpStatusCode.NotFound;
            Exception      ex         = null;

            TestRuntime.RunAsync(DateTime.Now.AddSeconds(30), async() => {
                try {
                    var result = await client.GetAsync($"https://httpbin.org/basic-auth/{validUsername}/{validPassword}");
                    httpStatus = result.StatusCode;
                } catch (Exception e) {
                    ex = e;
                } finally {
                    done = true;
                }
            }, () => done);

            if (!done)               // timeouts happen in the bots due to dns issues, connection issues etc.. we do not want to fail
            {
                Assert.Inconclusive("Request timedout.");
            }
            else
            {
                if (httpStatus == HttpStatusCode.BadGateway || httpStatus == HttpStatusCode.GatewayTimeout)
                {
                    TestRuntime.IgnoreInCI("Transient network failure - ignore in CI");
                }
                Assert.IsNull(ex, "Exception not null");
                Assert.AreEqual(expectedStatus, httpStatus, "Status not ok");
            }
        }
コード例 #7
0
        public void TestNSurlSessionHandlerCookieContainerSetCookie()
        {
            var url             = NetworkResources.Httpbin.GetSetCookieUrl("cookie", "chocolate-chip");
            var cookieContainer = new CookieContainer();

            string    nativeCookieResult = null;
            Exception ex        = null;
            var       completed = false;

            TestRuntime.RunAsync(DateTime.Now.AddSeconds(30), async() => {
                try {
                    var nativeHandler = new NSUrlSessionHandler()
                    {
                        AllowAutoRedirect = true,
                        CookieContainer   = cookieContainer,
                    };
                    var nativeClient   = new HttpClient(nativeHandler);
                    var nativeResponse = await nativeClient.GetAsync(url);
                    nativeCookieResult = await nativeResponse.Content.ReadAsStringAsync();
                } catch (Exception e) {
                    ex = e;
                } finally {
                    completed = true;
                }
            }, () => completed);

            if (!completed)
            {
                TestRuntime.IgnoreInCI("Transient network failure - ignore in CI");
            }
            Assert.IsTrue(completed, "Network request completed");
            Assert.IsNull(ex, "Exception");
            Assert.IsNotNull(nativeCookieResult, "Native cookies result");
            var cookiesFromServer = cookieContainer.GetCookies(new Uri(url));

            Assert.AreEqual(1, cookiesFromServer.Count, "Cookies received from server.");
        }
コード例 #8
0
        public void CreateResponseAuth()
        {
            CFHTTPMessage response             = null;
            var           done                 = false;
            var           taskCompletionSource = new TaskCompletionSource <CFHTTPMessage> ();

            // the following code has to be in a diff thread, else, we are blocking the current loop, not cool
            // perform a request so that we fail in the auth, then create the auth object and check the count
            TestRuntime.RunAsync(DateTime.Now.AddSeconds(30), async() => {
                using (var request = CFHTTPMessage.CreateRequest(
                           new Uri(NetworkResources.Httpbin.GetStatusCodeUrl(HttpStatusCode.Unauthorized)), "GET", null)) {
                    request.SetBody(Array.Empty <byte> ());                     // empty body, we are not interested
                    using (var stream = CFStream.CreateForHTTPRequest(request)) {
                        Assert.IsNotNull(stream, "Null stream");
                        // we are only interested in the completed event
                        stream.ClosedEvent += (sender, e) => {
                            taskCompletionSource.SetResult(stream.GetResponseHeader());
                            done = true;
                        };
                        // enable events and run in the current loop
                        stream.EnableEvents(CFRunLoop.Main, CFRunLoop.ModeDefault);
                        stream.Open();
                        response = await taskCompletionSource.Task;
                    }
                }
            }, () => done);
            if (!done)
            {
                TestRuntime.IgnoreInCI("Transient network failure - ignore in CI");
            }
            Assert.IsTrue(done, "Network request completed");
            using (var auth = CFHTTPAuthentication.CreateFromResponse(response)) {
                Assert.NotNull(auth, "Null Auth");
                Assert.IsTrue(auth.IsValid, "Auth is valid");
                Assert.That(TestRuntime.CFGetRetainCount(auth.Handle), Is.EqualTo((nint)1), "RetainCount");
            }
        }
コード例 #9
0
 public void TestProxyConfigured()
 {
     TestRuntime.IgnoreInCI("CI bots might have proxies setup and will mean that the test will fail.");
     Assert.IsFalse(report.ProxyConfigured, "Proxy configured.");
 }
コード例 #10
0
 public void TestUsedProxy()
 {
     TestRuntime.IgnoreInCI("CI bots might have proxies setup and will mean that the test will fail.");
     Assert.IsFalse(report.UsedProxy, "Used proxy");
 }
コード例 #11
0
 public void TestProxyEnpoint()
 {
     TestRuntime.IgnoreInCI("CI bots might have proxies setup and will mean that the test will fail.");
     Assert.IsNull(report.ProxyEndpoint);
 }
コード例 #12
0
        public void GHIssue8344()
        {
            var username = "******";
            var password = "******";
            var url      = $"https://httpbin.org/basic-auth/{username}/{password}";
            // perform two requests, one that will get a 200 with valid creds, one that wont and assert that
            // the second call does get a 401
            // create a http client to use with some creds that we do know are not valid
            var firstHandler = new NSUrlSessionHandler()
            {
                Credentials = new NetworkCredential(username, password, "")
            };

            var firstClient = new HttpClient(firstHandler);

            bool           done       = false;
            HttpStatusCode httpStatus = HttpStatusCode.NotFound;
            Exception      ex         = null;

            TestRuntime.RunAsync(DateTime.Now.AddSeconds(30), async() => {
                try {
                    var result = await firstClient.GetAsync(url);
                    httpStatus = result.StatusCode;
                } catch (Exception e) {
                    ex = e;
                } finally {
                    done = true;
                }
            }, () => done);

            if (!done)               // timeouts happen in the bots due to dns issues, connection issues etc.. we do not want to fail
            {
                Assert.Inconclusive("First request timedout.");
            }
            else
            {
                if (httpStatus == HttpStatusCode.BadGateway || httpStatus == HttpStatusCode.GatewayTimeout)
                {
                    TestRuntime.IgnoreInCI("Transient network failure - ignore in CI");
                }
                Assert.IsNull(ex, "First request exception not null");
                Assert.AreEqual(HttpStatusCode.OK, httpStatus, "First status not ok");
            }
            // exactly same operation, diff handler, wrong password, should fail

            var secondHandler = new NSUrlSessionHandler()
            {
                Credentials = new NetworkCredential(username, password + password, "")
            };

            var secondClient = new HttpClient(secondHandler);

            done       = false;
            httpStatus = HttpStatusCode.NotFound;
            ex         = null;
            TestRuntime.RunAsync(DateTime.Now.AddSeconds(30), async() => {
                try {
                    var result = await secondClient.GetAsync(url);
                    httpStatus = result.StatusCode;
                } catch (Exception e) {
                    ex = e;
                } finally {
                    done = true;
                }
            }, () => done);

            if (!done)               // timeouts happen in the bots due to dns issues, connection issues etc.. we do not want to fail
            {
                Assert.Inconclusive("Second request timedout.");
            }
            else
            {
                if (httpStatus == HttpStatusCode.BadGateway || httpStatus == HttpStatusCode.GatewayTimeout)
                {
                    TestRuntime.IgnoreInCI("Transient network failure - ignore in CI");
                }
                Assert.IsNull(ex, "Second request exception not null");
                Assert.AreEqual(HttpStatusCode.Unauthorized, httpStatus, "Second status not ok");
            }
        }