public void GetAllCookies()
        {
            if (!CheckIsOnValidHostNameForCookieTests())
            {
                return;
            }

            string key1 = GenerateUniqueKey();
            string key2 = GenerateUniqueKey();

            AssertCookieIsNotPresentWithName(key1);
            AssertCookieIsNotPresentWithName(key2);
            
            ReadOnlyCollection<Cookie> cookies = driver.Manage().Cookies.AllCookies;
            int count = cookies.Count;

            Cookie one = new Cookie(key1, "value");
            Cookie two = new Cookie(key2, "value");

            driver.Manage().Cookies.AddCookie(one);
            driver.Manage().Cookies.AddCookie(two);

            driver.Url = simpleTestPage;
            cookies = driver.Manage().Cookies.AllCookies;
            Assert.AreEqual(count + 2, cookies.Count);

            Assert.IsTrue(cookies.Contains(one));
            Assert.IsTrue(cookies.Contains(two));
        }
Пример #2
1
 public void GivenIAmLoggedIn()
 {
     var ticket = new FormsAuthenticationTicket(1, "*****@*****.**", DateTime.Now, DateTime.Now.AddDays(4), false, String.Empty);
     string encrypted = FormsAuthentication.Encrypt(ticket);
     var cookie = new Cookie(FormsAuthentication.FormsCookieName, encrypted);
     Driver.Manage().Cookies.AddCookie(cookie);
 }
        public void CookieIntegrity()
        {
            string url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs("animals");

            driver.Url = url;
            driver.Manage().DeleteAllCookies();

            DateTime time = DateTime.Now.AddDays(1);
            Cookie cookie1 = new Cookie("fish", "cod", null, "/common/animals", time);
            IOptions options = driver.Manage();
            options.AddCookie(cookie1);

            ReadOnlyCollection<Cookie> cookies = options.GetCookies();
            Cookie retrievedCookie = null;
            foreach (Cookie tempCookie in cookies)
            {
                if (cookie1.Equals(tempCookie))
                {
                    retrievedCookie = tempCookie;
                    break;
                }
            }

            Assert.IsNotNull(retrievedCookie);
            //Cookie.equals only compares name, domain and path
            Assert.AreEqual(cookie1, retrievedCookie);
        }
Пример #4
0
        public void AddCookiesWithDifferentPathsThatAreRelatedToOurs()
        {
            if (!CheckIsOnValidHostNameForCookieTests())
            {
                return;
            }

            string basePath = EnvironmentManager.Instance.UrlBuilder.Path;

            Cookie cookie1 = new Cookie("fish", "cod", "/" + basePath + "/animals");
            Cookie cookie2 = new Cookie("planet", "earth", "/" + basePath + "/");
            IOptions options = driver.Manage();
            options.Cookies.AddCookie(cookie1);
            options.Cookies.AddCookie(cookie2);

            UrlBuilder builder = EnvironmentManager.Instance.UrlBuilder;
            driver.Url = builder.WhereIs("animals");

            ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies;
            AssertCookieIsPresentWithName(cookie1.Name);
            AssertCookieIsPresentWithName(cookie2.Name);

            driver.Url = builder.WhereIs("simpleTest.html");
            AssertCookieIsNotPresentWithName(cookie1.Name);
        }
Пример #5
0
        public void CanSetCookiesOnADifferentPathOfTheSameHost()
        {
            if (!CheckIsOnValidHostNameForCookieTests())
            {
                return;
            }

            string basePath = EnvironmentManager.Instance.UrlBuilder.Path;
            Cookie cookie1 = new Cookie("fish", "cod", "/" + basePath + "/animals");
            Cookie cookie2 = new Cookie("planet", "earth", "/" + basePath + "/galaxy");

            IOptions options = driver.Manage();
            ReadOnlyCollection<Cookie> count = options.Cookies.AllCookies;

            options.Cookies.AddCookie(cookie1);
            options.Cookies.AddCookie(cookie2);

            string url = EnvironmentManager.Instance.UrlBuilder.WhereIs("animals");
            driver.Url = url;
            ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies;

            Assert.IsTrue(cookies.Contains(cookie1));
            Assert.IsFalse(cookies.Contains(cookie2));

            driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("galaxy");
            cookies = options.Cookies.AllCookies;
            Assert.IsFalse(cookies.Contains(cookie1));
            Assert.IsTrue(cookies.Contains(cookie2));
        }
Пример #6
0
        public void ShouldThrowExceptionWhenAddingCookieToAPageThatIsNotHtml()
        {
            driver.Url = textPage;

            Cookie cookie = new Cookie("hello", "goodbye");
            driver.Manage().Cookies.AddCookie(cookie);
        }
Пример #7
0
 public void AddCookieTest()
 {
     HomePage.WebDriver.Manage().Cookies.DeleteAllCookies();
     new Check().IsTrue(HomePage.WebDriver.Manage().Cookies.AllCookies.Count == 0);                                 
     Cookie cookie = new Cookie("key", "value");
     ContactFormPage.AddCookie(cookie);
     new Check().AreEquals(HomePage.WebDriver.Manage().Cookies.GetCookieNamed(cookie.Name).Value, cookie.Value);            
 }
Пример #8
0
 public void ClearCacheTest()
 {
     Cookie cookie = new Cookie("key", "value");
     HomePage.WebDriver.Manage().Cookies.AddCookie(cookie);
     new Check().IsFalse(HomePage.WebDriver.Manage().Cookies.AllCookies.Count == 0);            
     ContactFormPage.ClearCache();
     new Check().IsTrue(HomePage.WebDriver.Manage().Cookies.AllCookies.Count == 0);                                 
 }
        public void ShouldBeAbleToAddCookie()
        {
            if (!CheckIsOnValidHostNameForCookieTests())
            {
                return;
            }

            string key = GenerateUniqueKey();
            string value = "foo";
            Cookie cookie = new Cookie(key, value);
            AssertCookieIsNotPresentWithName(key);

            driver.Manage().Cookies.AddCookie(cookie);

            AssertCookieHasValue(key, value);
            Assert.That(driver.Manage().Cookies.AllCookies.Contains(cookie), "Cookie was not added successfully");
        }
Пример #10
0
        /// <summary>
        /// Handles the command.
        /// </summary>
        /// <param name="driver">The driver used to execute the command.</param>
        /// <param name="locator">The first parameter to the command.</param>
        /// <param name="value">The second parameter to the command.</param>
        /// <returns>The result of the command.</returns>
        protected override object HandleSeleneseCommand(IWebDriver driver, string locator, string value)
        {
            if (!this.NameValuePairRegex.IsMatch(locator))
            {
                throw new SeleniumException("Invalid parameter: " + locator);
            }

            Match nameValueMatch = this.NameValuePairRegex.Match(locator);
            string cookieName = nameValueMatch.Groups[1].Value;
            string cookieValue = nameValueMatch.Groups[2].Value;

            DateTime? maxAge = null;
            if (this.MaxAgeRegex.IsMatch(value))
            {
                Match maxAgeMatch = this.MaxAgeRegex.Match(value);
                maxAge = DateTime.Now.AddSeconds(int.Parse(maxAgeMatch.Groups[1].Value, CultureInfo.InvariantCulture));
            }

            string path = string.Empty;
            if (this.PathRegex.IsMatch(value))
            {
                Match pathMatch = this.PathRegex.Match(value);
                path = pathMatch.Groups[1].Value;
                try
                {
                    if (path.StartsWith("http", StringComparison.Ordinal))
                    {
                        path = new Uri(path).AbsolutePath;
                    }
                }
                catch (UriFormatException)
                {
                    // Fine.
                }
            }
            else
            {
                path = new Uri(driver.Url).AbsolutePath;
            }

            Cookie cookie = new Cookie(cookieName, cookieValue, path, maxAge);
            driver.Manage().Cookies.AddCookie(cookie);

            return null;
        }
        public void AddCookiesWithDifferentPathsThatAreRelatedToOurs()
        {
            string basePath = EnvironmentManager.Instance.UrlBuilder.Path;

            Cookie cookie1 = new Cookie("fish", "cod", "/" + basePath + "/animals");
            Cookie cookie2 = new Cookie("planet", "earth", "/" + basePath + "/");
            IOptions options = driver.Manage();
            options.AddCookie(cookie1);
            options.AddCookie(cookie2);

            UrlBuilder builder = EnvironmentManager.Instance.UrlBuilder;
            driver.Url = builder.WhereIs("animals");

            ReadOnlyCollection<Cookie> cookies = options.GetCookies();
            Assert.IsTrue(cookies.Contains(cookie1));
            Assert.IsTrue(cookies.Contains(cookie2));

            driver.Url = builder.WhereIs("");
            cookies = options.GetCookies();
            Assert.IsFalse(cookies.Contains(cookie1));
            Assert.IsTrue(cookies.Contains(cookie2));
        }
Пример #12
0
 /// <summary>
 /// Add cokie
 /// </summary>
 /// <param name="driver"></param>
 /// <param name="cookie"></param>
 public void AddCookie(IWebDriver driver, string cookieName, string cookie)
 {
     OpenQA.Selenium.Cookie ck = new OpenQA.Selenium.Cookie(cookieName, cookie);
     driver.Manage().Cookies.AddCookie(ck);
 }
Пример #13
0
        public void ShouldWalkThePathToDeleteACookie()
        {
            if (!CheckIsOnValidHostNameForCookieTests())
            {
                return;
            }

            string basePath = EnvironmentManager.Instance.UrlBuilder.Path;

            Cookie cookie1 = new Cookie("fish", "cod");
            driver.Manage().Cookies.AddCookie(cookie1);
            int count = driver.Manage().Cookies.AllCookies.Count;

            driver.Url = childPage;
            Cookie cookie2 = new Cookie("rodent", "hamster", "/" + basePath + "/child");
            driver.Manage().Cookies.AddCookie(cookie2);
            count = driver.Manage().Cookies.AllCookies.Count;

            driver.Url = grandchildPage;
            Cookie cookie3 = new Cookie("dog", "dalmation", "/" + basePath + "/child/grandchild/");
            driver.Manage().Cookies.AddCookie(cookie3);
            count = driver.Manage().Cookies.AllCookies.Count;

            driver.Url = (EnvironmentManager.Instance.UrlBuilder.WhereIs("child/grandchild"));
            driver.Manage().Cookies.DeleteCookieNamed("rodent");
            count = driver.Manage().Cookies.AllCookies.Count;

            Assert.IsNull(driver.Manage().Cookies.GetCookieNamed("rodent"));

            ReadOnlyCollection<Cookie> cookies = driver.Manage().Cookies.AllCookies;
            Assert.AreEqual(2, cookies.Count);
            Assert.IsTrue(cookies.Contains(cookie1));
            Assert.IsTrue(cookies.Contains(cookie3));

            driver.Manage().Cookies.DeleteAllCookies();
            driver.Url = grandchildPage;
            AssertNoCookiesArePresent();
        }
Пример #14
0
        public void ShouldReturnNullBecauseCookieRetainsExpiry()
        {
            if (!CheckIsOnValidHostNameForCookieTests())
            {
                return;
            }

            string url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs("animals");
            driver.Url = url;

            driver.Manage().Cookies.DeleteAllCookies();

            Cookie addCookie = new Cookie("fish", "cod", "/common/animals", DateTime.Now.AddHours(-1));
            IOptions options = driver.Manage();
            options.Cookies.AddCookie(addCookie);

            Cookie retrieved = options.Cookies.GetCookieNamed("fish");
            Assert.IsNull(retrieved);
        }
Пример #15
0
        public void ShouldNotShowCookieAddedToDifferentPath()
        {
            if (!CheckIsOnValidHostNameForCookieTests())
            {
                return;
            }

            // Cookies cannot be set on domain names with less than 2 dots, so
            // localhost is out. If we are in that boat, bail the test.
            string hostName = EnvironmentManager.Instance.UrlBuilder.HostName;
            string[] hostNameParts = hostName.Split(new char[] { '.' });
            if (hostNameParts.Length < 3)
            {
                Assert.Ignore("Skipping test: Cookies can only be set on fully-qualified domain names.");
            }

            driver.Url = macbethPage;
            IOptions options = driver.Manage();
            Cookie cookie = new Cookie("Lisa", "Simpson", EnvironmentManager.Instance.UrlBuilder.HostName, "/" + EnvironmentManager.Instance.UrlBuilder.Path + "IDoNotExist", null);
            options.Cookies.AddCookie(cookie);
            ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies;
            Assert.IsFalse(cookies.Contains(cookie), "Invalid cookie was returned");
        }
Пример #16
0
        public void ShouldNotGetCookiesRelatedToCurrentDomainWithoutLeadingPeriod()
        {
            if (!CheckIsOnValidHostNameForCookieTests())
            {
                return;
            }

            string cookieName = "name";
            AssertCookieIsNotPresentWithName(cookieName);

            Regex replaceRegex = new Regex(".*?\\.");
            string shorter = replaceRegex.Replace(this.hostname, ".", 1);
            Cookie cookie = new Cookie(cookieName, "value", shorter, "/", GetTimeInTheFuture());
            driver.Manage().Cookies.AddCookie(cookie);
            AssertCookieIsNotPresentWithName(cookieName);
        }
Пример #17
0
        public void ShouldNotBeAbleToSetDomainToSomethingThatIsUnrelatedToTheCurrentDomain()
        {
            if (!CheckIsOnValidHostNameForCookieTests())
            {
                return;
            }

            Cookie cookie1 = new Cookie("fish", "cod");
            IOptions options = driver.Manage();
            options.Cookies.AddCookie(cookie1);

            string url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs("simpleTest.html");
            driver.Url = url;

            Assert.IsNull(options.Cookies.GetCookieNamed("fish"));
        }
Пример #18
0
        public void CanSetCookieWithoutOptionalFieldsSet()
        {
            if (!CheckIsOnValidHostNameForCookieTests())
            {
                return;
            }

            string key = GenerateUniqueKey();
            string value = "foo";
            Cookie cookie = new Cookie(key, value);
            AssertCookieIsNotPresentWithName(key);

            driver.Manage().Cookies.AddCookie(cookie);

            AssertCookieHasValue(key, value);
        }
Пример #19
0
        public async Task <bool> Login(long simCardNumber)
        {
            try
            {
                _driver = Utility.RefreshDriver(_driver);
                if (!_driver.Url.Contains("divar.ir"))
                {
                    _driver.Navigate().GoToUrl("https://divar.ir");
                }

                var simBusiness = await SimcardBussines.GetAsync(simCardNumber);

                var tokenInDatabase = simBusiness?.DivarToken ?? null;

                var listLinkItems = _driver.FindElements(By.TagName("a"));
                var isLogined     = listLinkItems.Any(linkItem => linkItem.Text == @"خروج");

                //اگر کاربر لاگین شده فعلی همان کاربر مورد نظر است نیازی به لاگین نیست
                if (isLogined && !string.IsNullOrEmpty(tokenInDatabase))
                {
                    var currentTokenOnDivar = _driver.Manage().Cookies.GetCookieNamed("token").Value;
                    if (!string.IsNullOrEmpty(currentTokenOnDivar) && currentTokenOnDivar == tokenInDatabase)
                    {
                        return(true);
                    }
                }

                //اگر کاربرلاگین شده کاربر مد نظر ما نیست از آن کاربری خارج می شود
                if (isLogined)
                {
                    _driver.Manage().Cookies.DeleteCookieNamed("_gat");
                    _driver.Manage().Cookies.DeleteCookieNamed("token");
                }

                //در صورتیکه توکن قبلا ثبت شده باشد لاگین می کند
                if (!string.IsNullOrEmpty(tokenInDatabase))
                {
                    var token = new Cookie("token", tokenInDatabase);
                    _driver.Manage().Cookies.AddCookie(token);
                    _driver.Navigate().Refresh();
                }
                //اگر قبلا توکن نداشته وارد صفحه دریافت کد تائید لاگین می شود
                else
                {
                    _driver.Navigate().GoToUrl("https://divar.ir/my-divar/my-posts");
                    //کلیک روی دکمه ورود و ثبت نام
                    await Utility.Wait();

                    _driver.FindElement(By.ClassName("login-message__login-btn")).Click();
                    await Utility.Wait();

                    var currentWindow = _driver.CurrentWindowHandle;
                    _driver.SwitchTo().Window(currentWindow);
                    if (_driver.FindElements(By.Name("mobile")).Count > 0)
                    {
                        _driver.FindElement(By.Name("mobile")).SendKeys("0" + simCardNumber);
                    }
                }

                //انتظار برای لاگین شدن
                int repeat = 0;
                //حدود 120 ثانیه فرصت لاگین دارد
                while (repeat < 20)
                {
                    //تا زمانی که لاگین اوکی نشده باشد این حلقه تکرار می شود
                    listLinkItems = _driver.FindElements(By.TagName("a"));
                    if (listLinkItems.Count < 5)
                    {
                        return(false);
                    }

                    var isLogin = listLinkItems.Any(linkItem => linkItem.Text == @"خروج");

                    if (isLogin)
                    {
                        //var all = _driver.Manage().Cookies.AllCookies.ToList();
                        tokenInDatabase = _driver.Manage().Cookies.GetCookieNamed("token").Value;
                        if (simBusiness is null)
                        {
                            simBusiness = new SimcardBussines()
                            {
                                Guid = Guid.NewGuid()
                            }
                        }
                        ;

                        simBusiness.DivarToken = tokenInDatabase;
                        simBusiness.Modified   = DateTime.Now;
                        simBusiness.Number     = simCardNumber;

                        await simBusiness.SaveAsync();

                        ((IJavaScriptExecutor)_driver).ExecuteScript(@"alert('لاگین انجام شد');");
                        await Utility.Wait();

                        _driver.SwitchTo().Alert().Accept();
                        return(true);
                    }

                    var name = await SimcardBussines.GetAsync(simCardNumber);

                    var message = $@"مالک: {name.OwnerName} \r\nشماره: {name.Number}  \r\nلطفا لاگین نمائید ";
                    ((IJavaScriptExecutor)_driver).ExecuteScript($"alert('{message}');");

                    await Utility.Wait(3);

                    try
                    {
                        _driver.SwitchTo().Alert().Accept();
                        await Utility.Wait(3);

                        repeat++;
                    }
                    catch
                    {
                        await Utility.Wait(10);
                    }
                }
                return(false);
            }
            catch (WebException) { return(false); }
            catch (Exception ex)
            {
                if (ex.Source != "WebDriver")
                {
                    WebErrorLog.ErrorInstence.StartErrorLog(ex);
                }
                return(false);
            }
        }
        public void ShouldNotShowCookieAddedToDifferentPath()
        {
            if (!CheckIsOnValidHostNameForCookieTests())
            {
                return;
            }

            driver.Url = macbethPage;
            IOptions options = driver.Manage();
            Cookie cookie = new Cookie("Lisa", "Simpson", EnvironmentManager.Instance.UrlBuilder.HostName, "/" + EnvironmentManager.Instance.UrlBuilder.Path + "IDoNotExist", null);
            options.Cookies.AddCookie(cookie);
            ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies;
            Assert.IsFalse(cookies.Contains(cookie), "Invalid cookie was returned");
        }
Пример #21
0
        public ActionResult <IEnumerable <string> > Get()
        {
            ChromeOptions options = new ChromeOptions();

            options.AddExtensions(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ModHeader.crx"));
            List <string> customPages = new List <string>();

            //customPages.Add("company/profile?id=100369");
            //customPages.Add("company/stock?id=100369");
            //customPages.Add("company/corporateStructure?Id=100369");
            //customPages.Add("company/capitalOfferings?ID=100369");
            //customPages.Add("company/rankingReport?ID=100369");
            customPages.Add("company/detailedRatesReport?ID=100369");
            customPages.Add("company/rateSpecials?ID=100369");
            //customPages.Add("company/rateSpecials?ID=100369");
            //customPages.Add("company/branchCompetitors?ID=100369");
            var watch = System.Diagnostics.Stopwatch.StartNew();

            RemoteWebDriver driver = new RemoteWebDriver(new Uri("http://10.0.2.15:31799/wd/hub/"), options.ToCapabilities(), TimeSpan.FromSeconds(600));

            //driver.Navigate().GoToUrl("chrome-extension://cilllgpaahohggfdioeinnncmaecaeni/icon.png");
            driver.Navigate().GoToUrl("https://www.snlnet.com/snl.services.export.service/whoami.asp");

            var UserCookie = System.IO.File.ReadAllText(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "cookie.txt"));

            // CookieContainer ccon = new CookieContainer();
            // ccon.SetCookies(new Uri("https://www.snlnet.com"), UserCookie);

            foreach (var item in CookieValue(UserCookie))
            {
                OpenQA.Selenium.Cookie ck = new OpenQA.Selenium.Cookie(item.Key, item.Value);

                driver.Manage().Cookies.AddCookie(ck);
            }

            //(driver).ExecuteScript("localStorage.setItem('profiles', JSON.stringify({Cookie:'" + UserCookie + "'}));");
            List <string> manifestList = new List <string>();

            for (int i = 0; i < customPages.Count; i++)
            {
                var blankURL = "about:blank";
                driver.Navigate().GoToUrl(blankURL);
                //driver.Navigate().GoToUrl(string.Format("https://platform.midevcld.spglobal.com/web/client?auth=inherit#{0}&rbExportType=Pdf&kss=&ReportBuilderQuery=1", customPages[i]));
                driver.Navigate().GoToUrl(string.Format("https://www.snlnet.com/web/client?auth=inherit#{0}&rbExportType=Pdf&kss=&ReportBuilderQuery=1", customPages[i]));
                driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(30);
                string manifest = "Not Set";
                try
                {
                    manifest = driver.FindElement(By.Name("reportManifest")).GetAttribute("innerHTML");
                    manifestList.Add(manifest);
                }
                catch (Exception ex)
                {
                    manifestList.Add("Failed for " + customPages[i]);
                }
            }
            driver.Close();
            driver.Dispose();
            watch.Stop();
            manifestList.Add(", Total Elapsed seconds:" + watch.Elapsed.TotalSeconds);
            return(manifestList);
        }
Пример #22
0
        public void ShouldDeleteCookie()
        {
            if (!CheckIsOnValidHostNameForCookieTests())
            {
                return;
            }

            driver.Url = macbethPage;
            IOptions options = driver.Manage();
            Cookie cookieToDelete = new Cookie("answer", "42");
            Cookie cookieToKeep = new Cookie("canIHaz", "Cheeseburguer");
            options.Cookies.AddCookie(cookieToDelete);
            options.Cookies.AddCookie(cookieToKeep);
            ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies;
            options.Cookies.DeleteCookie(cookieToDelete);
            ReadOnlyCollection<Cookie> cookies2 = options.Cookies.AllCookies;
            Assert.IsFalse(cookies2.Contains(cookieToDelete), "Cookie was not deleted successfully");
            Assert.That(cookies2.Contains(cookieToKeep), "Valid cookie was not returned");
        }
Пример #23
0
        public void ShouldIgnoreThePortNumberOfTheHostWhenSettingTheCookie()
        {
            if (!CheckIsOnValidHostNameForCookieTests())
            {
                return;
            }

            // Cookies cannot be set on domain names with less than 2 dots, so
            // localhost is out. If we are in that boat, bail the test.
            string hostName = EnvironmentManager.Instance.UrlBuilder.HostName;
            string[] hostNameParts = hostName.Split(new char[] { '.' });
            if (hostNameParts.Length < 3)
            {
                Assert.Ignore("Skipping test: Cookies can only be set on fully-qualified domain names.");
            }

            Uri uri = new Uri(driver.Url);
            string host = string.Format("{0}:{1}", uri.Host, uri.Port);
            string cookieName = "name";
            AssertCookieIsNotPresentWithName(cookieName);
            Cookie cookie = new Cookie(cookieName, "value", host, "/", null);
            driver.Manage().Cookies.AddCookie(cookie);
            AssertCookieIsPresentWithName(cookieName);
        }
Пример #24
0
        public void GetCookieDoesNotRetriveBeyondCurrentDomain()
        {
            if (!CheckIsOnValidHostNameForCookieTests())
            {
                return;
            }

            Cookie cookie1 = new Cookie("fish", "cod");
            IOptions options = driver.Manage();
            options.Cookies.AddCookie(cookie1);

            String url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs("");
            driver.Url = url;

            ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies;
            Assert.IsFalse(cookies.Contains(cookie1));
        }
Пример #25
0
        public void ShouldNotDeleteCookiesWithASimilarName()
        {
            if (!CheckIsOnValidHostNameForCookieTests())
            {
                return;
            }

            string cookieOneName = "fish";
            Cookie cookie1 = new Cookie(cookieOneName, "cod");
            Cookie cookie2 = new Cookie(cookieOneName + "x", "earth");
            IOptions options = driver.Manage();
            AssertCookieIsNotPresentWithName(cookie1.Name);

            options.Cookies.AddCookie(cookie1);
            options.Cookies.AddCookie(cookie2);

            AssertCookieIsPresentWithName(cookie1.Name);

            options.Cookies.DeleteCookieNamed(cookieOneName);

            Assert.IsFalse(driver.Manage().Cookies.AllCookies.Contains(cookie1));
            Assert.IsTrue(driver.Manage().Cookies.AllCookies.Contains(cookie2));
        }
Пример #26
0
        public void SettingACookieThatExpiredInThePast()
        {
            string url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs("animals");

            driver.Url = url;
            driver.Manage().Cookies.DeleteAllCookies();

            DateTime expires = DateTime.Now.AddSeconds(-1000);
            Cookie cookie = new Cookie("expired", "yes", "/common/animals", expires);
            IOptions options = driver.Manage();
            options.Cookies.AddCookie(cookie);

            cookie = options.Cookies.GetCookieNamed("expired");
            Assert.IsNull(cookie, "Cookie expired before it was set, so nothing should be returned: " + cookie);
        }
Пример #27
0
        public void ShouldNotShowCookieAddedToDifferentDomain()
        {
            if (!CheckIsOnValidHostNameForCookieTests())
            {
                Assert.Ignore("Not on a standard domain for cookies (localhost doesn't count).");
            }

            driver.Url = macbethPage;
            IOptions options = driver.Manage();
            Cookie cookie = new Cookie("Bart", "Simpson", EnvironmentManager.Instance.UrlBuilder.HostName + ".com", EnvironmentManager.Instance.UrlBuilder.Path, null);
            Assert.Throws<WebDriverException>(() => options.Cookies.AddCookie(cookie));
            ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies;
            Assert.IsFalse(cookies.Contains(cookie), "Invalid cookie was returned");
        }
Пример #28
0
 /// <summary>
 /// Private constructor.
 /// (Use public builder methods instead.)
 /// </summary>
 /// <param name="cookie">The cookie to add to the WebDriver.</param>
 private AddBrowserCookie(OpenQA.Selenium.Cookie cookie) => Cookie = cookie;
Пример #29
0
        public void ShouldRetainCookieExpiry()
        {
            if (!CheckIsOnValidHostNameForCookieTests())
            {
                return;
            }

            string url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs("animals");

            driver.Url = url;
            driver.Manage().Cookies.DeleteAllCookies();

            // DateTime.Now contains milliseconds; the returned cookie expire date
            // will not. So we need to truncate the milliseconds.
            DateTime current = DateTime.Now;
            DateTime expireDate = new DateTime(current.Year, current.Month, current.Day, current.Hour, current.Minute, current.Second, DateTimeKind.Local).AddDays(1);

            Cookie addCookie = new Cookie("fish", "cod", "/common/animals", expireDate);
            IOptions options = driver.Manage();
            options.Cookies.AddCookie(addCookie);

            Cookie retrieved = options.Cookies.GetCookieNamed("fish");
            Assert.IsNotNull(retrieved);
            Assert.AreEqual(addCookie.Expiry, retrieved.Expiry, "Cookies are not equal");
        }
Пример #30
0
        public void ShouldBeAbleToAddToADomainWhichIsRelatedToTheCurrentDomain()
        {
            if (!CheckIsOnValidHostNameForCookieTests())
            {
                return;
            }

            // Cookies cannot be set on domain names with less than 2 dots, so
            // localhost is out. If we are in that boat, bail the test.
            string hostName = EnvironmentManager.Instance.UrlBuilder.HostName;
            string[] hostNameParts = hostName.Split(new char[] { '.' });
            if (hostNameParts.Length < 3)
            {
                Assert.Ignore("Skipping test: Cookies can only be set on fully-qualified domain names.");
            }

            AssertCookieIsNotPresentWithName("name");

            Regex replaceRegex = new Regex(".*?\\.");
            string shorter = replaceRegex.Replace(this.hostname, "", 1);
            Cookie cookie = new Cookie("name", "value", shorter, "/", GetTimeInTheFuture());

            driver.Manage().Cookies.AddCookie(cookie);

            AssertCookieIsPresentWithName("name");
        }
Пример #31
0
        // TODO(JimEvans): Disabling this test for now. If your network is using
        // something like OpenDNS or Google DNS which you may be automatically
        // redirected to a search page, which will be a valid page and will allow a
        // cookie to be created. Need to investigate further.
        // [Test]
        // [ExpectedException(typeof(InvalidOperationException))]
        public void ShouldThrowExceptionWhenAddingCookieToNonExistingDomain()
        {
            if (!CheckIsOnValidHostNameForCookieTests())
            {
                return;
            }

            driver.Url = macbethPage;
            driver.Url = "doesnot.noireallyreallyreallydontexist.com";
            IOptions options = driver.Manage();
            Cookie cookie = new Cookie("question", "dunno");
            options.Cookies.AddCookie(cookie);
        }
Пример #32
0
        public void ShouldBeAbleToIncludeLeadingPeriodInDomainName()
        {
            if (!CheckIsOnValidHostNameForCookieTests())
            {
                return;
            }

            // Cookies cannot be set on domain names with less than 2 dots, so
            // localhost is out. If we are in that boat, bail the test.
            string hostName = EnvironmentManager.Instance.UrlBuilder.HostName;
            string[] hostNameParts = hostName.Split(new char[] { '.' });
            if (hostNameParts.Length < 3)
            {
                Assert.Ignore("Skipping test: Cookies can only be set on fully-qualified domain names.");
            }

            AssertCookieIsNotPresentWithName("name");

            // Replace the first part of the name with a period
            Regex replaceRegex = new Regex(".*?\\.");
            string shorter = replaceRegex.Replace(this.hostname, ".", 1);
            Cookie cookie = new Cookie("name", "value", shorter, "/", DateTime.Now.AddSeconds(100000));

            driver.Manage().Cookies.AddCookie(cookie);

            AssertCookieIsPresentWithName("name");
        }
Пример #33
0
        public static string initiateDriver(IList <RestResponseCookie> cookies, string pr, string delay, string captcha, string proxy)
        {
            try {
                List <Cookie> lst = new List <Cookie>();
                foreach (var cook in cookies)
                {
                    Cookie ss = new Cookie(cook.Name, cook.Value, "www.supremenewyork.com", "/", DateTime.Now.AddDays(1));
                    lst.Add(ss);
                }

                IWebDriver driver;

                var service = ChromeDriverService.CreateDefaultService();
                service.HideCommandPromptWindow = true;
                var useragents = new List <string> {
                    "Mozilla/5.0 (Windows NT 4.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.517 Safari/537.36", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1309.0 Safari/537.17"
                };
                int index = new Random().Next(useragents.Count);
                var name  = useragents[index];
                useragents.RemoveAt(index);

                ChromeOptions option = new ChromeOptions();


                //option.AddArgument("--ignore-certificate-errors");
                option.AddArguments("--window-size=600,800");
                //option.AddArguments("--user-data-dir=C:/Users/intel/AppData/Local/Google/Chrome/User Data");

                option.AddArguments("--user-agent='" + name + "'");
                //option.AddArguments("--headless");
                //option.PageLoadStrategy = PageLoadStrategy.Normal;

                driver = new ChromeDriver(service, option);
                var _cookies = driver.Manage().Cookies.AllCookies;
                driver.Manage().Cookies.DeleteAllCookies();

                //var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(2000));

                driver.Navigate().GoToUrl("https://www.supremenewyork.com/");
                foreach (Cookie cookie in lst)
                {
                    driver.Manage().Cookies.AddCookie(cookie);
                }
                //option.AddArguments("--headless");
                //option.PageLoadStrategy = PageLoadStrategy.Normal;

                driver.Navigate().GoToUrl("https://www.supremenewyork.com/checkout");
                var result = "";
                try
                {
                    result = fillDelivery(driver, pr, captcha, delay);
                }catch (Exception ex)
                {
                    result = ex.Message;
                    driver.Quit();
                }
                return(result);
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
        }
Пример #34
0
        public void ShouldBeAbleToSetDomainToTheCurrentDomain()
        {
            if (!CheckIsOnValidHostNameForCookieTests())
            {
                return;
            }

            // Cookies cannot be set on domain names with less than 2 dots, so
            // localhost is out. If we are in that boat, bail the test.
            string hostName = EnvironmentManager.Instance.UrlBuilder.HostName;
            string[] hostNameParts = hostName.Split(new char[] { '.' });
            if (hostNameParts.Length < 3)
            {
                Assert.Ignore("Skipping test: Cookies can only be set on fully-qualified domain names.");
            }

            Uri url = new Uri(driver.Url);
            String host = url.Host + ":" + url.Port.ToString();

            Cookie cookie1 = new Cookie("fish", "cod", host, "/", null);
            IOptions options = driver.Manage();
            options.Cookies.AddCookie(cookie1);

            driver.Url = javascriptPage;
            ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies;
            Assert.IsTrue(cookies.Contains(cookie1));
        }
Пример #35
0
        public void ShouldAddCookieToCurrentDomain()
        {
            if (!CheckIsOnValidHostNameForCookieTests())
            {
                return;
            }

            driver.Url = macbethPage;
            IOptions options = driver.Manage();
            Cookie cookie = new Cookie("Marge", "Simpson", "/");
            options.Cookies.AddCookie(cookie);
            ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies;
            Assert.That(cookies.Contains(cookie), "Valid cookie was not returned");
        }
Пример #36
0
        public OpenQA.Selenium.Cookie GetCookie()
        {
            Cookie ck = new Cookie(this.Name, this.Value, this.Domain, this.Path, this.Expiry);

            return(ck);
        }