Exemplo n.º 1
0
        public void RedirectionWithAuthorizationHeaders(Type handlerType)
        {
            TestRuntime.AssertSystemVersion(ApplePlatform.MacOSX, 10, 9, throwIfOtherPlatform: false);
            TestRuntime.AssertSystemVersion(ApplePlatform.iOS, 7, 0, throwIfOtherPlatform: false);

            bool      containsAuthorizarion = false;
            bool      containsHeaders       = false;
            string    json = "";
            bool      done = false;
            Exception ex   = null;

            TestRuntime.RunAsync(DateTime.Now.AddSeconds(30), async() =>
            {
                try {
                    HttpClient client  = new HttpClient(GetHandler(handlerType));
                    client.BaseAddress = NetworkResources.Httpbin.Uri;
                    var byteArray      = new UTF8Encoding().GetBytes("username:password");
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
                    var result = await client.GetAsync(NetworkResources.Httpbin.GetRedirectUrl(3));
                    // get the data returned from httpbin which contains the details of the requested performed.
                    json = await result.Content.ReadAsStringAsync();
                    containsAuthorizarion = json.Contains("Authorization");
                    containsHeaders       = json.Contains("headers");                 // ensure we do have the headers in the response
                } 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 (!containsHeaders)
            {
                Assert.Inconclusive("Response from httpbin does not contain headers, therefore we cannot ensure that if the authoriation is present.");
            }
            else
            {
                Assert.IsFalse(containsAuthorizarion, $"Authorization header did reach the final destination. {json}");
                Assert.IsNull(ex, $"Exception {ex} for {json}");
            }
        }
        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);

            Assert.IsNull(ex, "Exception");
            Assert.IsNotNull(managedCookieResult, "Managed cookies result");
            Assert.IsNotNull(nativeCookieResult, "Native cookies result");
            Assert.AreEqual(managedCookieResult, nativeCookieResult, "Cookies");
        }
Exemplo n.º 3
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);

            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.");
        }
Exemplo n.º 4
0
        [Ignore("System.EntryPointNotFoundException: AppleCryptoNative_SecKeychainItemCopyKeychain")]          // https://github.com/dotnet/runtime/issues/36897
#endif
        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);

            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");
        }
Exemplo n.º 5
0
        public void FSEventFileChangedTest()
        {
            string path = Path.Combine(dirPath, "TempFileToWatch.txt");
            var    taskCompletionSource  = new TaskCompletionSource <FSEventStreamEventsArgs> ();
            FSEventStreamEventsArgs args = null;

            TestRuntime.RunAsync(TimeSpan.FromSeconds(30), async() => {
                fsEventStream.Events += (sender, eventArgs) => {
                    taskCompletionSource.SetResult(eventArgs);
                    watchedFileChanged = true;
                };
                fsEventStream.ScheduleWithRunLoop(CFRunLoop.Current);
                fsEventStreamStarted = fsEventStream.Start();
                File.AppendAllText(path, "Hello World!");
                Assert.IsTrue(File.Exists(path));
                args = await taskCompletionSource.Task.ConfigureAwait(false);
            }, () => watchedFileChanged);

            Assert.IsNotNull(args, "Null args");
        }
Exemplo n.º 6
0
        public void DnsFailure(Type handlerType)
        {
            bool      done = false;
            Exception ex   = null;

            TestRuntime.RunAsync(DateTime.Now.AddSeconds(30), async() =>
            {
                try {
                    HttpClient client = new HttpClient(GetHandler(handlerType));
                    var s             = await client.GetStringAsync("http://doesnotexist.xamarin.com");
                } catch (Exception e) {
                    ex = e;
                } finally {
                    done = true;
                }
            }, () => done);

            Assert.IsNotNull(ex, "Exception");
            // The handlers throw different types of exceptions, so we can't assert much more than that something went wrong.
        }
Exemplo n.º 7
0
        public void DispatchBarrierAsync()
        {
            TestRuntime.AssertSystemVersion(PlatformName.iOS, 8, 0, throwIfOtherPlatform: false);
            TestRuntime.AssertSystemVersion(PlatformName.MacOSX, 10, 10, throwIfOtherPlatform: false);

            using (var queue = new DispatchQueue("DispatchBarrierAsync")) {
                var called   = false;
                var callback = new Action(() => called = true);
                queue.DispatchBarrierAsync(callback);
                TestRuntime.RunAsync(TimeSpan.FromSeconds(5), () => { }, () => called);
                Assert.IsTrue(called, "Called");

                called = false;
                using (var dg = new DispatchBlock(callback)) {
                    queue.DispatchBarrierAsync(dg);
                    dg.Wait(TimeSpan.FromSeconds(5));
                }
                Assert.IsTrue(called, "Called DispatchBlock");
            }
        }
        public void GuidedAccessConfigureAccessibilityFeaturesTest()
        {
            TestRuntime.AssertXcodeVersion(10, 2);

            var gotError   = false;
            var didSuccess = true;
            var done       = false;

            TestRuntime.RunAsync(DateTime.Now.AddSeconds(30), async() => {
                try {
                    var res    = await UIGuidedAccessRestriction.ConfigureAccessibilityFeaturesAsync(UIGuidedAccessAccessibilityFeature.Zoom, true);
                    gotError   = res.Error != null;               // We expect an error back from the API call.
                    didSuccess = res.Success;                     // We expect false since monotouch-tests app is not run in kiosk mode.
                } finally {
                    done = true;
                }
            }, () => done);

            Assert.NotNull(gotError, "Error was null.");
            Assert.IsFalse(didSuccess, "Somehow this succeeded, are we running monotouch-tests app in kiosk mode?");
        }
Exemplo n.º 9
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");
            }
        }
        public void NoRetainCyclesExpectedTest()
        {
            var thread = new Thread(delegate() {
                MyParentView.weakcount = 0;
                for (int i = 0; i < totalTestObjects; i++)
                {
                    var parent = new MyParentView(useWeak: true);
                    parent.TouchButton();
                }
            });

            thread.Start();
            thread.Join();

            GC.Collect(0);
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.WaitForPendingFinalizers();

            TestRuntime.RunAsync(DateTime.Now.AddSeconds(30), () => { }, () => MyParentView.weakcount < totalTestObjects);
            Assert.That(MyParentView.weakcount, Is.LessThan(totalTestObjects), "No retain cycles expected");
        }
Exemplo n.º 11
0
        void CallAnimateImage(bool useUrl, CGImageAnimation.CGImageSourceAnimationHandler handler)
        {
            tcs    = new TaskCompletionSource <bool> ();
            status = (CGImageAnimationStatus)1;              /* CGImageAnimationStatus.Ok == 0 */
            bool done = false;

            TestRuntime.RunAsync(TimeSpan.FromSeconds(30), async() => {
                if (useUrl)
                {
                    status = CGImageAnimation.AnimateImage(imageUrl, null, handler);
                }
                else
                {
                    status = CGImageAnimation.AnimateImage(imageData, null, handler);
                }
                await tcs.Task;
                done = true;
            },
                                 () => done);

            tcs = null;
        }
Exemplo n.º 12
0
        public void RegistrarTest()
        {
            Exception ex      = null;
            var       done    = new ManualResetEvent(false);
            var       success = false;

            Task.Run(async() => {
                try {
                    var config = NSUrlSessionConfiguration.DefaultSessionConfiguration;
                    config.WeakProtocolClasses = NSArray.FromNSObjects(new Class(typeof(CustomUrlProtocol)));
                    var session    = NSUrlSession.FromConfiguration(config);
                    var custom_url = new NSUrl("foo://server");
                    using (var task = await session.CreateDownloadTaskAsync(custom_url)) {
                        success = true;
                    }
                } catch (Exception e) {
                    ex = e;
                } finally {
                    done.Set();
                }
            });

            Assert.IsTrue(TestRuntime.RunAsync(DateTime.Now.AddSeconds(10), () => { }, () => done.WaitOne(0)), "Timed out");
            Assert.IsNull(ex, "Exception");
            Assert.IsTrue(custom_url_protocol_instance.Called_DidCompleteWithError, "DidCompleteWithError");
            // if DidReceiveChallenge is called or not seems to vary between test runs, so we can't assert it.
            //Assert.IsFalse (custom_url_protocol_instance.Called_DidReceiveChallenge, "DidReceiveChallenge");
            Assert.IsTrue(custom_url_protocol_instance.Called_DidReceiveData, "DidReceiveData");
            Assert.IsTrue(custom_url_protocol_instance.Called_DidReceiveResponse, "DidReceiveResponse");
            Assert.IsTrue(custom_url_protocol_instance.Called_StartLoading, "StartLoading");
            Assert.IsTrue(custom_url_protocol_instance.Called_StopLoading, "StopLoading");
            Assert.IsFalse(custom_url_protocol_instance.Called_WillPerformHttpRedirection, "WillPerformHttpRedirection");

            Assert.IsTrue(CustomUrlProtocol.Called_CanInitWithRequest, "CanInitWithRequest");
            Assert.IsTrue(CustomUrlProtocol.Called_GetCanonicalRequest, "GetCanonicalRequest");

            Assert.IsTrue(success, "Success");
        }
Exemplo n.º 13
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");
            }
        }
Exemplo n.º 14
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.");
        }
Exemplo n.º 15
0
        public void DownloadDataAsync()
        {
            TestRuntime.AssertXcodeVersion(5, 0);

            bool      completed        = false;
            int       failed_iteration = -1;
            Exception ex = null;

            TestRuntime.RunAsync(DateTime.Now.AddSeconds(30), async() => {
                try {
                    for (int i = 0; i < 5; i++)
                    {
                        // Use the default configuration so we can make use of the shared cookie storage.
                        var session = NSUrlSession.FromConfiguration(NSUrlSessionConfiguration.DefaultSessionConfiguration);

                        var downloadUri      = new Uri("https://google.com");
                        var downloadResponse = await session.CreateDownloadTaskAsync(downloadUri);

                        var tempLocation = downloadResponse.Location;
                        if (!File.Exists(tempLocation.Path))
                        {
                            Console.WriteLine("#{1} {0} does not exists", tempLocation, i);
                            failed_iteration = i;
                            break;
                        }
                    }
                } catch (Exception e) {
                    ex = e;
                } finally {
                    completed = true;
                }
            }, () => completed);

            Assert.IsNull(ex, "Exception");
            Assert.AreEqual(-1, failed_iteration, "Failed");
        }
Exemplo n.º 16
0
        public void TestPACParsingAsyncNoProxy()
        {
            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 script    = File.ReadAllText(pacPath);
            var targetUri = new Uri("http://docs.xamarin.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.ExecuteProxyAutoConfigurationScriptAsync(script, 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);
        }
        public void LoadHtmlAsync_NSUrl()
        {
            var    completed = false;
            string d         = Path.Combine(NSBundle.MainBundle.ResourcePath, "access-denied.html");
            string g         = Path.Combine(NSBundle.MainBundle.ResourcePath, "access-granted.html");

            TestRuntime.RunAsync(DateTime.Now.AddSeconds(3000), async() => {
                using (var denied = NSUrl.FromFilename(d))
                    using (var granted = NSUrl.FromFilename(g)) {
                        var options = new NSAttributedStringDocumentAttributes {
                            ReadAccessUrl = granted
                        };
                        var r1 = await NSAttributedString.LoadFromHtmlAsync(granted, options);
                        Assert.That(r1.AttributedString.Value, Is.EqualTo("Granted"), "granted by options");
#if false
                        // this does not match my interpretation of the (headers) docs
                        var r2 = await NSAttributedString.LoadFromHtmlAsync(denied, options);
                        Assert.That(r2.AttributedString.Value, Is.Not.EqualTo("Denied"), "denied by options");
#endif
                        completed = true;
                    }
            }, () => completed);
            Assert.True(completed, "completed");
        }
Exemplo n.º 18
0
        public void CreateDataTaskAsync()
        {
            if (!TestRuntime.CheckSystemAndSDKVersion(7, 0))
            {
                Assert.Inconclusive("requires iOS7");
            }

            NSUrlSession session = NSUrlSession.SharedSession;

            var url     = new NSUrl("http://www.xamarin.com");
            var tmpfile = Path.GetTempFileName();

            File.WriteAllText(tmpfile, "TMPFILE");
            var file_url  = NSUrl.FromFilename(tmpfile);
            var file_data = NSData.FromFile(tmpfile);
            var request   = new NSUrlRequest(url);

            var completed = false;
            var timeout   = 30;

            /* CreateDataTask */
            completed = false;
            Assert.IsTrue(TestRuntime.RunAsync(DateTime.Now.AddSeconds(timeout), async() => {
                await session.CreateDataTaskAsync(request);
                completed = true;
            }, () => completed), "CreateDataTask a");

            completed = false;
            Assert.IsTrue(TestRuntime.RunAsync(DateTime.Now.AddSeconds(timeout), async() => {
                await session.CreateDataTaskAsync(url);
                completed = true;
            }, () => completed), "CreateDataTask b");

            /* CreateDownloadTask */
            completed = false;
            Assert.IsTrue(TestRuntime.RunAsync(DateTime.Now.AddSeconds(timeout), async() => {
                await session.CreateDownloadTaskAsync(request);
                completed = true;
            }, () => completed), "CreateDownloadTask a");


            completed = false;
            Assert.IsTrue(TestRuntime.RunAsync(DateTime.Now.AddSeconds(timeout), async() => {
                await session.CreateDownloadTaskAsync(url);
                completed = true;
            }, () => completed), "CreateDownloadTask b");

            /* CreateUploadTask */
            completed = false;
            Assert.IsTrue(TestRuntime.RunAsync(DateTime.Now.AddSeconds(timeout), async() => {
                try {
                    await session.CreateUploadTaskAsync(request, file_url);
                } catch /* (Exception ex) */ {
//					Console.WriteLine ("Ex: {0}", ex);
                } finally {
                    completed = true;
                }
            }, () => completed), "CreateUploadTask a");

            completed = false;
            Assert.IsTrue(TestRuntime.RunAsync(DateTime.Now.AddSeconds(timeout), async() => {
                try {
                    await session.CreateUploadTaskAsync(request, file_data);
                } catch /* (Exception ex) */ {
//					Console.WriteLine ("Ex: {0}", ex);
                } finally {
                    completed = true;
                }
            }, () => completed), "CreateUploadTask b");
        }
Exemplo n.º 19
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
            {
                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
            {
                Assert.IsNull(ex, "Second request exception not null");
                Assert.AreEqual(HttpStatusCode.Unauthorized, httpStatus, "Second status not ok");
            }
        }
Exemplo n.º 20
0
        public void RejectSslCertificatesServicePointManager(Type handlerType)
        {
            TestRuntime.AssertSystemVersion(PlatformName.MacOSX, 10, 9, throwIfOtherPlatform: false);
            TestRuntime.AssertSystemVersion(PlatformName.iOS, 7, 0, throwIfOtherPlatform: false);

#if __MACOS__
            if (handlerType == typeof(NSUrlSessionHandler) && TestRuntime.CheckSystemVersion(PlatformName.MacOSX, 10, 10, 0) && !TestRuntime.CheckSystemVersion(PlatformName.MacOSX, 10, 11, 0))
            {
                Assert.Ignore("Fails on macOS 10.10: https://github.com/xamarin/maccore/issues/1645");
            }
#endif

            bool                validationCbWasExecuted                = false;
            bool                customValidationCbWasExecuted          = false;
            bool                invalidServicePointManagerCbWasExcuted = false;
            bool                done = false;
            Exception           ex   = null;
            Type                expectedExceptionType = null;
            HttpResponseMessage result = null;

            var handler = GetHandler(handlerType);
            if (handler is HttpClientHandler ch)
            {
                expectedExceptionType = typeof(AuthenticationException);
                ch.ServerCertificateCustomValidationCallback = (sender, certificate, chain, errors) => {
                    validationCbWasExecuted = true;
                    // return false, since we want to test that the exception is raised
                    return(false);
                };
                ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => {
                    invalidServicePointManagerCbWasExcuted = true;
                    return(false);
                };
            }
            else if (handler is NSUrlSessionHandler ns)
            {
                expectedExceptionType = typeof(WebException);
                ns.TrustOverride     += (a, b) => {
                    validationCbWasExecuted = true;
                    // return false, since we want to test that the exception is raised
                    return(false);
                };
            }
            else
            {
                Assert.Fail($"Invalid HttpMessageHandler: '{handler.GetType ()}'.");
            }

            TestRuntime.RunAsync(DateTime.Now.AddSeconds(30), async() =>
            {
                try {
                    HttpClient client  = new HttpClient(handler);
                    client.BaseAddress = NetworkResources.Httpbin.Uri;
                    var byteArray      = new UTF8Encoding().GetBytes("username:password");
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
                    result = await client.GetAsync(NetworkResources.Httpbin.GetRedirectUrl(3));
                } catch (Exception e) {
                    ex = e;
                } finally {
                    done = true;
                    ServicePointManager.ServerCertificateValidationCallback = null;
                }
            }, () => 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
            {
                // the ServicePointManager.ServerCertificateValidationCallback will never be executed.
                Assert.False(invalidServicePointManagerCbWasExcuted);
                Assert.True(validationCbWasExecuted);
                // assert the exception type
                Assert.IsNotNull(ex, (result == null)? "Expected exception is missing and got no result" : $"Expected exception but got {result.Content.ReadAsStringAsync ().Result}");
                Assert.IsInstanceOf(typeof(HttpRequestException), ex);
                Assert.IsNotNull(ex.InnerException);
                Assert.IsInstanceOf(expectedExceptionType, ex.InnerException);
            }
        }
Exemplo n.º 21
0
        public void CreateDataTaskAsync()
        {
            TestRuntime.AssertXcodeVersion(5, 0);

            NSUrlSession session = NSUrlSession.SharedSession;
            var          url     = new NSUrl("https://www.microsoft.com");
            var          tmpfile = Path.GetTempFileName();

            File.WriteAllText(tmpfile, "TMPFILE");
            var file_url  = NSUrl.FromFilename(tmpfile);
            var file_data = NSData.FromFile(tmpfile);
            var request   = new NSUrlRequest(url);

            var completed = false;
            var timeout   = 30;

            /* CreateDataTask */
            completed = false;
            Assert.IsTrue(TestRuntime.RunAsync(DateTime.Now.AddSeconds(timeout), async() => {
                await session.CreateDataTaskAsync(request);
                completed = true;
            }, () => completed), "CreateDataTask a");

            completed = false;
            Assert.IsTrue(TestRuntime.RunAsync(DateTime.Now.AddSeconds(timeout), async() => {
                await session.CreateDataTaskAsync(url);
                completed = true;
            }, () => completed), "CreateDataTask b");

            /* CreateDownloadTask */
            completed = false;
            Assert.IsTrue(TestRuntime.RunAsync(DateTime.Now.AddSeconds(timeout), async() => {
                await session.CreateDownloadTaskAsync(request);
                completed = true;
            }, () => completed), "CreateDownloadTask a");


            completed = false;
            Assert.IsTrue(TestRuntime.RunAsync(DateTime.Now.AddSeconds(timeout), async() => {
                await session.CreateDownloadTaskAsync(url);
                completed = true;
            }, () => completed), "CreateDownloadTask b");

            /* CreateUploadTask */
            completed = false;
            Assert.IsTrue(TestRuntime.RunAsync(DateTime.Now.AddSeconds(timeout), async() => {
                try {
                    var uploadRequest        = new NSMutableUrlRequest(url);
                    uploadRequest.HttpMethod = "POST";
                    await session.CreateUploadTaskAsync(uploadRequest, file_url);
                } catch /* (Exception ex) */ {
//					Console.WriteLine ("Ex: {0}", ex);
                } finally {
                    completed = true;
                }
            }, () => completed), "CreateUploadTask a");

            completed = false;
            Assert.IsTrue(TestRuntime.RunAsync(DateTime.Now.AddSeconds(timeout), async() => {
                try {
                    var uploadRequest        = new NSMutableUrlRequest(url);
                    uploadRequest.HttpMethod = "POST";
                    await session.CreateUploadTaskAsync(uploadRequest, file_data);
                } catch /* (Exception ex) */ {
//					Console.WriteLine ("Ex: {0}", ex);
                } finally {
                    completed = true;
                }
            }, () => completed), "CreateUploadTask b");
        }
Exemplo n.º 22
0
        void Trust_Leaf_Only(SecTrust trust, SecPolicy policy)
        {
            Assert.That(CFGetRetainCount(trust.Handle), Is.EqualTo((nint)1), "RetainCount(trust)");
            Assert.That(CFGetRetainCount(policy.Handle), Is.EqualTo((nint)2), "RetainCount(policy)");
            // that certificate stopped being valid on September 30th, 2013 so we validate it with a date earlier than that
            trust.SetVerifyDate(new DateTime(635108745218945450, DateTimeKind.Utc));
            // the system was able to construct the chain based on the single certificate
            var expectedTrust = SecTrustResult.RecoverableTrustFailure;

#if __MACOS__
            if (!TestRuntime.CheckSystemVersion(PlatformName.MacOSX, 10, 9))
            {
                expectedTrust = SecTrustResult.Unspecified;
            }
#endif
            Assert.That(Evaluate(trust, true), Is.EqualTo(expectedTrust), "Evaluate");

            using (var queue = new DispatchQueue("TrustAsync")) {
                bool assert = false;                 // we don't want to assert in another queue
                bool called = false;
                var  err    = trust.Evaluate(DispatchQueue.MainQueue, (t, result) => {
                    assert = t.Handle == trust.Handle && result == expectedTrust;
                    called = true;
                });
                Assert.That(err, Is.EqualTo(SecStatusCode.Success), "async1/err");
                TestRuntime.RunAsync(TimeSpan.FromSeconds(5), () => { }, () => called);
                Assert.True(assert, "async1");
            }

            if (TestRuntime.CheckXcodeVersion(11, 0))
            {
                using (var queue = new DispatchQueue("TrustErrorAsync")) {
                    bool assert = false;                     // we don't want to assert in another queue
                    bool called = false;
                    var  err    = trust.Evaluate(DispatchQueue.MainQueue, (t, result, error) => {
                        assert = t.Handle == trust.Handle && !result && error != null;
                        called = true;
                    });
                    Assert.That(err, Is.EqualTo(SecStatusCode.Success), "async2/err");
                    TestRuntime.RunAsync(TimeSpan.FromSeconds(5), () => { }, () => called);
                    Assert.True(assert, "async2");
                }
            }

#if __MACOS__
            var hasNetworkFetchAllowed = TestRuntime.CheckSystemVersion(PlatformName.MacOSX, 10, 9);
#else
            var hasNetworkFetchAllowed = TestRuntime.CheckXcodeVersion(5, 0);
#endif
            if (hasNetworkFetchAllowed)
            {
                Assert.True(trust.NetworkFetchAllowed, "NetworkFetchAllowed-1");
                trust.NetworkFetchAllowed = false;
                Assert.False(trust.NetworkFetchAllowed, "NetworkFetchAllowed-2");

                trust.SetPolicy(policy);

                var policies = trust.GetPolicies();
                Assert.That(policies.Length, Is.EqualTo(1), "Policies.Length");
                Assert.That(policies [0].Handle, Is.EqualTo(policy.Handle), "Handle");
            }
        }
Exemplo n.º 23
0
        public void TestStateChangesHandler()
        {
            // In the test we are doing the following:
            //
            // 1. Start a browser. At this point, we have no listeners (unless someone is exposing it in the lab)
            // and therefore the browser cannot find any services/listeners.
            // 2. Start a listener that is using the same type/domain pair that the browser expects.
            // 3. Browser picks up the new listener, and sends an event (service found).
            // 4. Listener stops, and the service disappears.
            // 5. The browser is not yet canceled, so it picks up that the service/listener is not longer then and returns it.
            //
            // The test will block until the different events are set by the callbacks that are executed in a diff thread.

            bool      firstRun      = true;
            bool      eventsDone    = false;
            bool      listeningDone = false;
            Exception ex            = null;
            var       changesEvent  = new AutoResetEvent(false);
            var       browserReady  = new AutoResetEvent(false);
            var       finalEvent    = new AutoResetEvent(false);

            TestRuntime.RunAsync(DateTime.Now.AddSeconds(30), async() => {
                // start the browser, before the listener
                browser.SetStateChangesHandler((st, er) => {
                    Assert.IsNotNull(st, "State");
                    Assert.IsNull(er, "Error");
                    if (st == NWBrowserState.Ready)
                    {
                        browserReady.Set();
                    }
                });
                browser.SetChangesHandler((oldResult, newResult) => {
                    // first time, listener appears, so we do not have an old result, second time
                    // listener goes, so we do not have a new result
                    try {
                        if (firstRun)
                        {
                            Assert.IsNull(oldResult, "oldResult first run.");
                            Assert.IsNotNull(newResult, "newResult first run");
                            firstRun = false;
                        }
                        else
                        {
                            Assert.IsNotNull(oldResult, "oldResult first run.");
                            Assert.IsNull(newResult, "newResult first run");
                        }
                    } catch (Exception e) {
                        ex = e;
                    } finally {
                        changesEvent.Set();
                        eventsDone = true;
                    }
                });
                browser.Start();
                browserReady.WaitOne(30000);
                using (var advertiser = NWAdvertiseDescriptor.CreateBonjourService("MonoTouchFixtures.Network", type))
                    using (var tcpOptions = NWProtocolOptions.CreateTcp())
                        using (var tlsOptions = NWProtocolOptions.CreateTls())
                            using (var paramenters = NWParameters.CreateTcp()) {
                                paramenters.ProtocolStack.PrependApplicationProtocol(tlsOptions);
                                paramenters.ProtocolStack.PrependApplicationProtocol(tcpOptions);
                                paramenters.IncludePeerToPeer = true;
                                using (var listener = NWListener.Create("1234", paramenters)) {
                                    listener.SetQueue(DispatchQueue.CurrentQueue);
                                    listener.SetAdvertiseDescriptor(advertiser);
                                    // we need the connection handler, else we will get an exception
                                    listener.SetNewConnectionHandler((c) => { });
                                    listener.SetStateChangedHandler((s, e) => {
                                        if (e != null)
                                        {
                                            Console.WriteLine($"Got error {e.ErrorCode} {e.ErrorDomain} '{e.CFError.FailureReason}' {e.ToString ()}");
                                        }
                                    });
                                    listener.Start();
                                    changesEvent.WaitOne(30000);
                                    listener.Cancel();
                                    listeningDone = true;
                                    finalEvent.Set();
                                }
                            }
            }, () => eventsDone);

            finalEvent.WaitOne(30000);
            Assert.IsTrue(eventsDone);
            Assert.IsTrue(listeningDone);
            Assert.IsNull(ex, "Exception");
            browser.Cancel();
        }
Exemplo n.º 24
0
 public void DrawTest()
 {
     // Render an image with a pattern, and show it briefly on screen.
     // It's supposed to show a blue oval with green plus signs inside.
     TestRuntime.RunAsync(DateTime.Now.AddSeconds(0.1), () => { }, () => true, GetRenderedPattern());
 }