Exemplo n.º 1
0
        public string Spa2102(ChromeDriver browser)
        {
            string ATAInfo = "Found SPA2102, just create a ticket a this point, this thing is an\nancient piece of junk that needs to be replaced. ";
            var    OrgURL  = browser.Url;

            try
            {
                //have to dismiss alert first go around, navigate to admin login page, THEN login
                browser.SwitchTo().Alert().Dismiss();
                browser.Navigate().GoToUrl(browser.Url + "/admin/advanced");
                browser.SwitchTo().Alert().SetAuthenticationCredentials(userName, passWord);

                var DarkRows  = browser.FindElementsByTagName("d3d3d3");
                var LightRows = browser.FindElementsByTagName("dcdcdc");
                var uptime    = DarkRows[4].FindElements(By.Id("td"));
                ATAInfo = $"Uptime: {uptime[3].Text}\nRebooted/Rebuit ATA. ";
                browser.Navigate().GoToUrl(OrgURL + "/admin/reboot");
                //BrowserHelper.CreateBrowser(browser.Url);
            }
            catch (NoAlertPresentException BadAlert)
            {
                Console.WriteLine($"No alert found when attempting reboot, are lines in use? ref: {BadAlert.ToString()}");
                ATAInfo += "No alert found when attempting reboot, are lines in use?";
            }
            catch (Exception e)
            {
                return(ATAInfo = $"Unknown Error occured. Please try again. Ref: {e.ToString()}");
            }

            return(ATAInfo);
        }
Exemplo n.º 2
0
        protected void btnDownloadFile_OnClick(object sender, EventArgs e)
        {
            if (!Page.IsValid)
            {
                ltrMessage.Text = "There is some missing information";
                return;
            }

            var driver = new ChromeDriver();

            if (string.IsNullOrEmpty(txtUrl.Text))
            {
                ltrMessage.Text = "Url cannot be null or empty string"; return;
            }
            var url = txtUrl.Text;

            driver.Url = url;

            //To maximize the window.
            driver.Manage().Window.Maximize();
            ScrollToBottom(driver);
            // For loading images
            var sleepTime = Convert.ToInt32(txtTimeToSleep.Text) * 1000;

            Thread.Sleep(sleepTime);

            var images = driver.FindElementsByTagName("img");

            DownloadImages(images);
            var divs = driver.FindElementsByTagName("div");

            DownloadImages(divs);

            driver.Close();
        }
Exemplo n.º 3
0
        public static string GetElementByTagName(string url, string tag, bool inTab = false)
        {
            OpenRefresh(url);
            var els = driver.FindElementsByTagName(tag);

            var sourceHtml = els.First().GetAttribute("innerHTML");

            return(sourceHtml);
        }
Exemplo n.º 4
0
        public async Task <bool> CheckAuth()
        {
            await Task.Delay(TimeSpan.FromSeconds(10));

            var spanList = _driver.FindElementsByTagName("span");

            return(await Task.Run(() =>
                                  !spanList.Any(span => span.Text.Equals("Log in to Cloudflare", StringComparison.OrdinalIgnoreCase))));
        }
Exemplo n.º 5
0
        private static void RunTests()
        {
            var options = new ChromeOptions();

            if (UseHeadless)
            {
                options.AddArgument("no-sandbox");
                options.AddArgument("headless");
            }

            options.AddArgument("window-size=1024x768");

            using var service = string.IsNullOrEmpty(ChromeDriverPath)
                                ? ChromeDriverService.CreateDefaultService()
                                : ChromeDriverService.CreateDefaultService(ChromeDriverPath);
            using var driver = new ChromeDriver(service, options);

            driver.Url = Url;

            var index          = 0;
            var currentTimeout = Timeout;

            do
            {
                var pre = driver.FindElementsByTagName("PRE").Skip(index).ToArray();
                if (pre.Length > 0)
                {
                    index         += pre.Length;
                    currentTimeout = Timeout;                     // reset the timeout

                    foreach (var e in pre)
                    {
                        Console.WriteLine(e.Text);
                    }
                }

                var resultsElement = driver.FindElementsById("results");
                if (resultsElement.Count == 0)
                {
                    if (driver.FindElementsByClassName("neterror").Count > 0)
                    {
                        var errorCode = driver.FindElementsByClassName("error-code").FirstOrDefault()?.Text;
                        throw new Exception($"There was an error loading the page: {errorCode}");
                    }

                    Thread.Sleep(500);
                    continue;
                }

                var text  = resultsElement[0].Text;
                var bytes = Convert.FromBase64String(text);
                File.WriteAllBytes(OutputPath, bytes);
                break;
            } while (--currentTimeout > 0);

            if (currentTimeout <= 0)
            {
                throw new TimeoutException();
            }
        }
Exemplo n.º 6
0
        public void GetListOfRecordsByCategory()
        {
            _driver.Navigate().GoToUrl(_url);

            var levelCount = GetLevelCount(_driver.FindElementsByTagName("tr"));

            for (var i = 0; i < levelCount; i++)
            {
                //this is the worst piece of code I have written
                try
                {
                    _driver.FindElementByXPath($"//*[@id=\"content\"]/table/tbody/tr[2]/td[2]/table/tbody/tr[{i + _indexToStartLevelsFrom}]/td[2]/a").Click();
                }
                catch (NoSuchElementException)
                {
                    //handle multiple game characters in the markup by using the first td tag instead of the second
                    _driver.FindElementByXPath($"//*[@id=\"content\"]/table/tbody/tr[2]/td[2]/table/tbody/tr[{i + _indexToStartLevelsFrom}]/td[1]/a").Click();
                }

                var url           = _driver.Url;
                var listOfRecords = new GetListOfRecordsForLevelService(url, _driver).GetListOfRecords();
                var csvContent    = new GetCsvFromRecordListService(listOfRecords).GetCsvFromRecordList();
                new SaveCsvToFileService(csvContent, url).SaveCsvToFile();
                _driver.Navigate().Back();
            }
        }
Exemplo n.º 7
0
        public void TestMethod1()
        {
            using (var driver = new ChromeDriver())
            {
                driver.Navigate().GoToUrl("file://C:/Users/mallu/source/repos/SeleniumTestApp/AdvanceAutomation/iframetest.html");

                new WebDriverWait(driver, TimeSpan.FromSeconds(5)).Until(
                    d => ((IJavaScriptExecutor)d).ExecuteScript("return document.readyState").Equals("complete"));

                var iframes = driver.FindElementsByTagName("iframe");
                Assert.IsTrue(iframes.Count == 2);

                driver.SwitchTo().Frame(0);
                var textFromzero = driver.PageSource.Contains("responsive sites");
                Assert.IsTrue(textFromzero);

                driver.SwitchTo().DefaultContent();

                driver.SwitchTo().Frame(1);
                var textFromOne = driver.PageSource.Contains("Online Bootcamp");
                Assert.IsTrue(textFromOne);

                //Console.Read();
            }
        }
Exemplo n.º 8
0
        public void GetColours(ChromeDriver driver)
        {
            var TextElements = driver.FindElementsByTagName("p");

            foreach (var TextElement in TextElements)
            {
                TextColours.Add(TextElement.GetCssValue("color"));

                if (TextElement.GetCssValue("background").Contains("rgba(0, 0, 0, 0)"))
                {
                    var TextElementParent = TextElement.FindElement(By.XPath("./.."));
                    while (TextElementParent.GetCssValue("background").Contains("rgba(0, 0, 0, 0)"))
                    {
                        TextElementParent = TextElementParent.FindElement(By.XPath("./.."));
                    }
                    BackgroundColours.Add(TextElementParent.GetCssValue("background"));
                    DivToShow.Add(string.Join(" ", TextElement.GetAttribute("innerHTML").ToString().Split().Take(3)));
                }
                else
                {
                    BackgroundColours.Add(TextElement.GetCssValue("background"));
                    DivToShow.Add(string.Join(" ", TextElement.GetAttribute("innerHTML").ToString().Split().Take(3)));
                }
            }
        }
Exemplo n.º 9
0
        public static void PegandoIPs()
        {
            var options = new ChromeOptions();
            //options.AddArguments("--headless");
            //options.AddArguments("--disable-gpu");
            //var proxy = new Proxy();
            //proxy.Kind = ProxyKind.Manual;
            //proxy.IsAutoDetect = false;
            //proxy.HttpProxy = proxy.SslProxy = "1.20.101.221:55707";
            //options.Proxy = proxy;
            //options.AddArgument("ignore-certificate-errors");
            var          chromeDriver = new ChromeDriver(@"C:\chromeDriver\teste\", options);
            var          numero       = 0;
            StreamWriter sw           = new StreamWriter(@"C:\chromeDriver\ip.txt");

            chromeDriver.Navigate().GoToUrl("https://hidemyna.me/en/proxy-list/?maxtime=500&type=s#list");
            System.Threading.Thread.Sleep(10000);
            var campos_proxy = chromeDriver.FindElementsByTagName("table")[0].FindElements(By.TagName("tr"));

            Console.WriteLine(campos_proxy[0].Text);
            //.FindElements(By.TagName("tr"));
            for (var x = 0; x < campos_proxy.Count; x++)
            {
                try
                {
                    var ip    = campos_proxy[x].FindElements(By.TagName("td"))[0].Text;
                    var porta = campos_proxy[x].FindElements(By.TagName("td"))[1].Text;
                    Console.WriteLine(ip + ":" + porta);
                    sw.WriteLine(ip + ":" + porta);
                }
                catch (Exception e) {}
                if (x == campos_proxy.Count - 1)
                {
                    if (numero == 640)
                    {
                        sw.Close();
                        break;
                    }
                    numero += 64;
                    chromeDriver.Navigate().GoToUrl("https://hidemyna.me/en/proxy-list/?maxtime=500&type=s&start=" + numero + "#list");
                    campos_proxy = chromeDriver.FindElementsByTagName("table")[0].FindElements(By.TagName("tr"));
                    x            = 0;
                }
            }
        }
        public void ThenICanNotFindBookWithTagAndName(string tag, string elementName)
        {
            ChromeDriver driver = SeleiumDriver;

            var elements = driver.FindElementsByTagName(tag);
            var actual   = (from e in elements
                            select e.Text);

            CollectionAssert.DoesNotContain(actual, elementName);
        }
Exemplo n.º 11
0
        public void TestMethod1()
        {
            var htmlReporter = new ExtentHtmlReporter
                                   (@"C:\Users\partha\Desktop\dream.html");
            var repo = new ExtentReports();

            repo.AttachReporter(htmlReporter);
            var test = repo.CreateTest("parta");

            var wd = new ChromeDriver();

            wd.Url = "https://www.google.com/";
            HttpWebRequest req  = null;
            var            tags = wd.FindElementsByTagName("a");

            Dictionary <string, string> li = new Dictionary <string, string>();

            int hi = 0;

            Parallel.ForEach(tags, k =>
            {
                hi++;
                string h = k.GetAttribute("href");
                try
                {
                    req          = (HttpWebRequest)WebRequest.Create(h);
                    var response = (HttpWebResponse)req.GetResponse();
                    //test.Info(h + "- " + response.StatusCode.ToString());
                    li.Add(h, response.StatusDescription.ToString());
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            });
            string[][] data = new string[li.Count][];
            int        i    = 0;

            try
            {
                foreach (KeyValuePair <string, string> item in li)
                {
                    data[i] = new string[2] {
                        item.Key, item.Value
                    };
                    i++;
                }
                test.Info(MarkupHelper.CreateTable(data));
                test.Info("rama");
            }
            catch (Exception) { }
            //ConvertDictionaryTo2dStringArray(li,test);
            repo.Flush();
            wd.Quit();
        }
Exemplo n.º 12
0
        public List <string> ScrapeTextInCiteTags()
        {
            var           citeTags  = _browserDriver.FindElementsByTagName("cite");
            List <string> citeTexts = new List <string>();

            foreach (var citeTag in citeTags)
            {
                citeTexts.Add(citeTag.Text);
            }
            return(citeTexts);
        }
Exemplo n.º 13
0
        public static void GetAllLinks()
        {
            ChromeDriver driver = new ChromeDriver();

            driver.Navigate().GoToUrl("https://www.belatrixsf.com/");
            IReadOnlyCollection <IWebElement> anchors = driver.FindElementsByTagName("a");

            foreach (IWebElement element in anchors)
            {
                Console.WriteLine($"Texto del link: {element.Text}");
            }
        }
Exemplo n.º 14
0
        public static string GetCurrentTrack()
        {
            if (!Spotify.IsAvailable())
            {
                return(string.Empty);
            }

            string song   = "";
            string artist = "";

            try
            {
                var links = _spotifyDriver.FindElementsByTagName("a");

                foreach (var link in links)
                {
                    if (string.IsNullOrEmpty(link.Text))
                    {
                        continue;
                    }

                    // TODO: could use CSS selectors?
                    var databind = link.GetAttribute("data-bind");

                    if (databind == null)
                    {
                        continue;
                    }

                    System.Diagnostics.Debug.WriteLine(databind);

                    if (databind.Contains("href: trackURI"))
                    {
                        song = link.Text;
                    }
                    else if (databind.Contains("trackURI") && link.GetAttribute("href").Contains("artist"))
                    {
                        artist = link.Text;
                    }
                }

                return(artist + " - " + song);
            }
            catch
            {
                // exceptions will occur if the Spotify content changes while it's being enumerated
                // for example, if the song occurs while we're looking for the song title
                return("");
            }
        }
Exemplo n.º 15
0
        private void kezelNapiBelepesiBonusz()
        {
            if (kezeltFalu == botAccFo || kezeltFalu == sajatFo)
            {
                try
                {
                    vezerlo.FindElementsByTagName("a").Last(l => l.Text.Contains("Kinyit")).Click();

                    if (kezeltFalu == botAccFo)
                    {
                        kiirFileba("Robot napi bónusz beváltva ekkor:\t" + DateTime.Now, "RobotBonusz.txt");
                    }
                    else if (kezeltFalu == sajatFo)
                    {
                        kiirFileba("Afromokus napi bónusz beváltva ekkor:\t" + DateTime.Now, "SajatBonuszIdo.txt");
                    }
                }
                catch //(Exception hiba)
                {
                    //MessageBox.Show(hiba.Message);
                }
            }
        }
        public void EndToEndTest()
        {
            ChromeDriver.Navigate().GoToUrl(GetAbsoluteUrl("/"));
            ChromeDriver.FindElementByLinkText("Log in").Click();
            ChromeDriver.FindElementById("UserName").SendKeys("admin");
            ChromeDriver.FindElementById("Password").SendKeys("!nf0suPP0r7");
            ChromeDriver.FindElementsByTagName("form")[1].Submit();
            ChromeDriver.FindElementByLinkText("Start Programmeren").Click();
            ChromeDriver.FindElementByLinkText("Start de tijd!").Click();
            ChromeDriver.FindElementByLinkText("Editor").Click();
            ChromeDriver.FindElementByLinkText("Submit").Click();
            ChromeDriver.FindElementById("assignmentSubmitModal").FindElement(By.LinkText("Submit")).Click();

            Thread.Sleep(5000);
        }
        public List <Record> GetListOfRecords()
        {
            var listOfRecords = new List <Record>();

            _driver.Navigate().GoToUrl(_url);

            var recordsCount = GetRecordCount(_driver.FindElementsByTagName("tr"));

            for (var i = 0; i < recordsCount; i++)
            {
                _driver.FindElementByXPath($"//*[@id=\"content\"]/table/tbody/tr[2]/td[2]/table/tbody/tr[{i + ROWS_TO_COUNT_AHEAD_WHEN_GETTING_XPATH}]/td[3]/a").Click();

                var historyRecordsAsList = GetListOfRecordText(_driver.FindElementsByTagName("tr"));

                for (var j = 0; j < historyRecordsAsList.Length; j++)
                {
                    var historyRowData = historyRecordsAsList[j].Split(" ");
                    var comment        = GetCommentFromHistoryRowData(historyRowData);

                    listOfRecords.Add(new Record
                    {
                        Player = _driver.Url.Split("/")[URL_PLAYER_INDEX],
                        //stat and date require some validation from bad data (yay)
                        Stat     = !historyRowData[RECORD_ROW_STAT_INDEX].Contains("/") ? historyRowData[RECORD_ROW_STAT_INDEX] : listOfRecords[listOfRecords.Count - 1].Stat,
                        Date     = historyRowData[RECORD_ROW_DATE_INDEX].Contains("-") ? historyRowData[RECORD_ROW_DATE_INDEX] : historyRowData[RECORD_ROW_DATE_INDEX - 1],
                        Comment  = comment,
                        HasProof = comment.Contains("youtube.com") || comment.Contains("twitch.tv") || comment.Contains("youtu.be")
                    });
                }

                listOfRecords[listOfRecords.Count - 1].IsMostRecent = true;
                _driver.Navigate().Back();
            }

            return(listOfRecords);
        }
        public void WhenIClickOnTheLinkWithTheTextTheAdjacentColumnOfTheElementName(string elementName)
        {
            const string TableRowTag  = "tr";
            const string TableDataTag = "td";
            const string LinkTag      = "a";

            ChromeDriver driver = SeleiumDriver;

            var rows      = driver.FindElementsByTagName(TableRowTag);
            var soughtRow = (from row in rows
                             where row.FindElement(By.TagName(TableDataTag)).Text == elementName
                             select row).First();
            var link = soughtRow.FindElement(By.TagName(LinkTag));

            link.Click();
        }
Exemplo n.º 19
0
        private ICollection <IWebElement> FindAllButton()
        {
            ICollection <IWebElement> displayedList = new List <IWebElement>();
            var listOfElement = _driver.FindElementsByTagName("tr");

            foreach (var element in listOfElement)
            {
                var aaa   = element.GetAttribute("style");
                var aaass = element.GetAttribute("class");

                if (element.GetAttribute("style") == "display: table-row;")
                {
                    displayedList.Add(element);
                }
            }
            return(displayedList);
        }
        public void WhenIClickOnTheButtonWithTheTextTheAdjacentColumnOfTheItem(string elementName)
        {
            const string TableRowTag  = "tr";
            const string TableDataTag = "td";
            const string FormTag      = "form";
            const string ButtonTag    = "button";

            ChromeDriver driver = SeleiumDriver;

            var rows      = driver.FindElementsByTagName(TableRowTag);
            var soughtRow = (from row in rows
                             where row.FindElement(By.TagName(TableDataTag)).Text == elementName
                             select row).First();
            var button = soughtRow.FindElement(By.TagName(FormTag)).FindElement(By.TagName(ButtonTag));

            button.Click();
        }
Exemplo n.º 21
0
 public void TestCaseOne()
 {
     using (var driver = new ChromeDriver())
     {
         driver.Navigate().GoToUrl("file://D:/seleniun using dot net framework/SeleniumTests/Advance Automation/iframetest.html");
         new WebDriverWait(driver, TimeSpan.FromSeconds(5)).Until(d => ((IJavaScriptExecutor)d)
                                                                  .ExecuteScript("return document.readyState").Equals("complete"));
         var iframes = driver.FindElementsByTagName("iframe");
         Assert.IsTrue(iframes.Count == 2);
         driver.SwitchTo().Frame(0);
         var text = driver.PageSource.Contains("responsive sites");
         Assert.IsTrue(text);
         driver.SwitchTo().DefaultContent();//if we want to switch diiferent iframes, use this method
         driver.SwitchTo().Frame(1);
         var text2 = driver.PageSource.Contains("Online Bootcamp");
         Assert.IsTrue(text2);
     }
 }
        /// <summary>
        /// Scrape page links if they are not visited and if they <see cref="ShouldCrawlLink"/>
        /// </summary>
        /// <param name="driver"></param>
        private void ScrapePageLinks(ChromeDriver driver)
        {
            var hrefs = driver.FindElementsByTagName("a").Select(t => t.GetAttribute("href"));

            foreach (var href in hrefs)
            {
                if (href == null)
                {
                    continue;
                }

                if (!_visitedLinks.ContainsKey(href) && ShouldCrawlLink(href))
                {
                    AddVisitedLink(href);
                    this._pagesQueue.Enqueue(href);
                }
            }
        }
Exemplo n.º 23
0
        public void CheckHelth()
        {
            var wd = new ChromeDriver();

            wd.Url = "https://www.google.com/";
            HttpWebRequest req  = null;
            var            tags = wd.FindElementsByTagName("a");

            string h    = "";
            var    list = new List <string>();

            Parallel.ForEach(tags, k =>
            {
                try
                {
                    h            = (wd as IJavaScriptExecutor).ExecuteScript("return arguments[0].href", k).ToString();
                    req          = (HttpWebRequest)WebRequest.Create(h);
                    var response = (HttpWebResponse)req.GetResponse();
                    list.Add(h + "|" + response.StatusCode);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            });
            DataTable dat = new DataTable("HTTPS");

            dat.Columns.Add("Page Title", typeof(String));
            dat.Columns.Add("URL", typeof(String));
            dat.Columns.Add("StatusCode", typeof(String));
            foreach (var item in list)
            {
                dat.Rows.Add(wd.Title, item.Split('|')[0], item.Split('|')[1]);
            }
            var          d        = ConvertDataTableToHtml(dat);
            string       filename = @"dream1.html";
            StreamWriter swXLS    = new StreamWriter(filename);

            swXLS.Write(d);
            swXLS.Close();

            wd.Quit();
        }
Exemplo n.º 24
0
        public async Task <IHttpActionResult> Get(string hashtag)
        {
            ChromeOptions options = new ChromeOptions();

            // if you like to specify another profile
            //options.AddArguments("headless");
            options.AddArguments("user-data-dir=/root/Downloads/aaa");
            options.AddArguments("start-maximized");
            ChromeDriver driver = new ChromeDriver(options);

            driver.Navigate().GoToUrl("https://www.instagram.com/explore/tags/" + hashtag + "/");

            var linkCollection = driver.FindElementsByTagName("a");

            IJavaScriptExecutor js = (IJavaScriptExecutor)driver;

            for (int i = 0; i <= 20; i++)
            {
                js.ExecuteScript("window.scrollTo(0,88800);");
                Thread.Sleep(1000);
            }

            var webElements = driver.FindElements(By.CssSelector("._mck9w._gvoze._tn0ps")).ToList();

            List <string> sourceList = new List <string>();

            foreach (var webElement in webElements)
            {
                var videoHtml = webElement.GetAttribute("outerHTML");
                if (videoHtml.Contains("_my8ed"))
                {
                    sourceList.Add(videoHtml);
                }
            }

            driver.Dispose();

            return(Ok(sourceList));
        }
Exemplo n.º 25
0
        public void VerifyPageTitle(int startDay, string startMonth, int startYear, int endDay, string endMonth, int endYear)
        {
            // Replace with your own test logic
            driver.Url = "https://*****:*****@id='dropdown']"));

            dropdown.Click();

            IWebElement dropdownChanged = driver.FindElement(By.XPath("//div[2]/button[@id='option' and @class='dropdown-item' and 1]"));

            dropdownChanged.Click();

            #region StartDate
            IWebElement startDate = driver.FindElement(By.XPath("//input[1]"));
            startDate.Click();

            IWebElement startDateYear = driver.FindElement(By.XPath("//select[2]"));
            startDateYear.Click();


            var selects     = driver.FindElementsByTagName("select");
            var month       = selects[0];
            var years       = selects[1];
            var optionsYear = years.FindElements(By.TagName("option"));
            var elemYear    = optionsYear.FirstOrDefault(item => item.Text == startYear.ToString());
            elemYear.Click();

            var optionsMonth = month.FindElements(By.TagName("option"));
            var elemMonth    = optionsMonth.FirstOrDefault(item => item.Text == startMonth);
            elemMonth.Click();

            IWebElement startDateChangeDay = driver.FindElement(By.XPath($"//div[@class='btn-light' and text()='{startDay}']"));
            startDateChangeDay.Click();
            #endregion

            #region EndDate
            IWebElement endDate = driver.FindElement(By.XPath("//input[2]"));
            endDate.Click();

            IWebElement endDateYear = driver.FindElement(By.XPath("//select[2]"));
            endDateYear.Click();


            selects     = driver.FindElementsByTagName("select");
            month       = selects[0];
            years       = selects[1];
            optionsYear = years.FindElements(By.TagName("option"));
            elemYear    = optionsYear.FirstOrDefault(item => item.Text == endYear.ToString());
            elemYear.Click();

            optionsMonth = month.FindElements(By.TagName("option"));
            elemMonth    = optionsMonth.FirstOrDefault(item => item.Text == endMonth);
            elemMonth.Click();

            IWebElement endDateChangeDay = driver.FindElement(By.XPath($"//div[@class='btn-light' and text()='{endDay}']"));
            endDateChangeDay.Click();
            #endregion

            startDate = driver.FindElement(By.XPath("//input[1]"));
            endDate   = driver.FindElement(By.XPath("//input[2]"));
            string s1   = startDate.GetProperty("value");
            string s2   = endDate.GetProperty("value");
            bool   res1 = s1.Equals($"{DateTime.ParseExact(startMonth, "MMM", System.Globalization.CultureInfo.CurrentCulture).Month}/{startDay}/{startYear}");
            bool   res2 = s2.Equals($"{DateTime.ParseExact(endMonth, "MMM", System.Globalization.CultureInfo.CurrentCulture).Month}/{endDay}/{endYear}");

            Assert.AreEqual(true, res1 && res2);
        }
Exemplo n.º 26
0
        public void OpenLinkInMenu()
        {
            var FileName = @"D:\Selenium\TestCase\OpenLinkInMenu";
            var Files    = Directory.GetFiles(FileName, "*.json");

            foreach (var sFile in Files)
            {
                var          Json           = File.ReadAllText(sFile);
                var          Dict           = JsonConvert.DeserializeObject <Dictionary <string, string> >(Json);
                var          SelectedOption = (SelectTestModel)StackPanel_SelectOptions.DataContext;
                ChromeDriver chrome         = new ChromeDriver();
                chrome.Manage().Window.Maximize();
                chrome.Url = "http://soliddevapp.allianceitsc.com/#/login/up";
                chrome.Navigate();
                Thread.Sleep(5000);
                var    ScreenShotPath = Dict["ScreenShotPath"];
                var    LogPath        = Dict["LogPath"];
                var    Log            = "TEST CASE: " + Dict["Description"] + '\n';
                string LoginError     = Login(chrome, Dict["UserName"], Dict["Password"], Dict["ScreenShotPath"]);
                if (LoginError != "")
                {
                    Log += "Login error, stop testing!\n" + LoginError;
                    File.WriteAllText(Dict["LogPath"] + "Log.txt", Log);
                    chrome.Quit();
                    return;
                }
                Log += ChangeServerApi(chrome, Dict["UserName"], Dict["Password"], Dict["Server"], Dict["ScreenShotPath"]);
                var Logo = chrome.FindElementById("brandlogo");
                Logo.Click();
                Thread.Sleep(1500);
                var OpenMenu = chrome.FindElementByXPath("//*[@id='root']/div/div[4]/header/button[1]/span");
                OpenMenu.Click();
                Thread.Sleep(1000);
                var Links = chrome.FindElementsByTagName("a");
                Dictionary <string, bool> Flag = new Dictionary <string, bool>();
                foreach (var sLink in Links)
                {
                    if (sLink.Text != "")
                    {
                        Flag[sLink.Text] = true;
                    }
                }
                foreach (var sLink in Links)
                {
                    if (sLink.Text != "")
                    {
                        sLink.Click();
                        Thread.Sleep(1500);
                        var SubLink = chrome.FindElementsByTagName("a");
                        foreach (var sSubLink in SubLink)
                        {
                            if (sSubLink.Text != "" && !Flag.ContainsKey(sSubLink.Text))
                            {
                                sSubLink.Click();
                                Thread.Sleep(5000);
                                chrome.SwitchTo().Window(chrome.WindowHandles[1]);
                                Log += VerifyError(chrome, ScreenShotPath);
                                if (SelectedOption.IsOpenTab)
                                {
                                    Log += OpenAllTabInPage(chrome, ScreenShotPath);
                                }
                                if (SelectedOption.IsOpenExpander)
                                {
                                    Log += OpenExpander(chrome, ScreenShotPath);
                                }
                                chrome.Close();
                                chrome.SwitchTo().Window(chrome.WindowHandles[0]);
                                Thread.Sleep(1000);
                                File.WriteAllText(LogPath + "Log.txt", Log);
                                break;
                            }
                        }
                        sLink.Click();
                        Thread.Sleep(1500);
                    }
                }
                Log += '\n';
                File.WriteAllText(LogPath + "Log.txt", Log);
                chrome.Quit();
            }
        }
Exemplo n.º 27
0
 public static IWebElement FindLabelByText(this ChromeDriver driver, string text)
 {
     return(driver.FindElementsByTagName("label").Single(l => l.Text == text));
 }
Exemplo n.º 28
0
 /// <summary>
 /// Получить элементы по тэгу
 /// </summary>
 /// <param name="tagName">Наименование тэга</param>
 /// <returns>Коллекция вэб-элементов</returns>
 public IEnumerable <IWebElement> GetElementsByTagName(string tagName)
 {
     return(_chromeDriver.FindElementsByTagName(tagName));
 }
        internal bool HasAvailableFlights()
        {
            var listOfFlights = driver.FindElementsByTagName("flight-row");

            return(listOfFlights.Any());
        }
Exemplo n.º 30
0
        //---------------------------------------------------------------------------------------------parte 2 PRUEBA MATRIZ----------------------------------------------------------------------------
        //----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
        //----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------



        //public void HacerPruebaMatriz(string link, string carpeta, string txt_pruebas)
        public List <string> HacerPruebaMatriz(string link, string carpeta, string txt_pruebas)
        {
            List <string> listaCapturas = new List <string>();

            try
            {
                StreamWriter  sw           = new StreamWriter($"{carpeta}/Test.txt");
                StreamReader  leerPruebas  = new StreamReader($"{txt_pruebas}");
                List <string> ListaPruebas = new List <string>();

                while (!leerPruebas.EndOfStream)
                {
                    ListaPruebas.Add(leerPruebas.ReadLine());
                }
                leerPruebas.Close();
                foreach (var elemento in ListaPruebas)
                {
                    Console.WriteLine(elemento);
                    Thread.Sleep(200);
                }
                //sw.Close();
                //iniciamos el chromeDriver
                var options = new ChromeOptions();
                //options.AddArgument("--disable-gpu");

                var chromeDriver = new ChromeDriver(options);     //The chromedriver.exe file does not exist in the current directory or in a directory on the PATH environment variable
                Thread.Sleep(7000);
                chromeDriver.Manage().Window.Maximize();
                chromeDriver.Navigate().GoToUrl(link);


                Thread.Sleep(7000);


                var titulos = chromeDriver.FindElementsByTagName("input");



                List <Selector> selector = new List <Selector>();

                List <string> listaID   = new List <string>();
                List <string> listaName = new List <string>();
                List <string> listaType = new List <string>();

                //------------------------------------------------extraigo los id y name------------------------------------------------


                foreach (var titulo in titulos)
                {
                    try
                    {
                        //Console.WriteLine(titulo.Text);


                        if ((titulo.GetAttribute("id") != null) && (titulo.GetAttribute("id") != "" && titulo.GetAttribute("id") != "--no-sandbox"))
                        {
                            Selector sl = new Selector();
                            sw.WriteLine("--------------------------------------------------------------------------------");
                            Console.WriteLine("--------------------------------------------------------------------------------");
                            Console.WriteLine("id:    " + titulo.GetAttribute("id"));
                            Console.WriteLine("type:  " + titulo.GetAttribute("type"));
                            Console.WriteLine("name:  " + titulo.GetAttribute("name"));


                            sl.Id = Convert.ToString(titulo.GetAttribute("id"));
                            sw.WriteLine(titulo.GetAttribute("id"));
                            sl.Type = Convert.ToString(titulo.GetAttribute("type"));
                            sw.WriteLine(titulo.GetAttribute("type"));
                            sl.Name = Convert.ToString(titulo.GetAttribute("name"));
                            sw.WriteLine(titulo.GetAttribute("name"));

                            selector.Add(sl);
                        }
                        //Console.WriteLine("name:  " + titulo.GetAttribute("name"));
                        Console.WriteLine("");

                        Thread.Sleep(100);
                    }
                    catch (Exception) { }
                }


                //----------------------------------------------------------------------------fin busqueda de selectores -----------------------------------
                //le relizo pruebas a los formularios y los evaluo
                ScreenCapture sc  = new ScreenCapture();
                Image         img = sc.CaptureScreen();
                //extraigo la fecha y hora para el nombre de la carpeta
                //DateTime thisDay = DateTime.Today;

                string direccionCapturas = $"{carpeta}/";
                string formato           = ".png";
                sc.CaptureScreenToFile(direccionCapturas + "Test" + formato, ImageFormat.Png);
                //chromeDriver.Quit();


                //Console.WriteLine("llego hasta aqui");

                foreach (var elementoID in selector)
                {
                    //Console.WriteLine("");
                    //Console.WriteLine(elementoID.Type);
                    //Console.WriteLine("");
                    if (elementoID.Type == "text" || elementoID.Type == "email" || elementoID.Type == "password")
                    {
                        var ingreso = chromeDriver.FindElementById(elementoID.Id);
                        try
                        {
                            foreach (var elemento in ListaPruebas)
                            {
                                Console.WriteLine("id: " + elementoID);
                                sw.WriteLine("id: " + elementoID);

                                Thread.Sleep(1000);
                                ingreso.SendKeys(elemento);
                                if (ingreso.Text != null)
                                {
                                    Thread.Sleep(500);
                                    sw.WriteLine($"En el id:{elementoID.Id} el texto {elemento} esta permitido");
                                    Console.WriteLine($"En el id:{elementoID.Id} el texto {elemento} esta permitido");
                                    ingreso.Submit();

                                    //ingreso = chromeDriver.FindElementById(elementoID.Id);
                                    sc.CaptureScreenToFile(direccionCapturas + elementoID.Id + elemento + formato, ImageFormat.Png);
                                    listaCapturas.Add(direccionCapturas + elementoID.Id + elemento + formato);
                                    Thread.Sleep(400);
                                }

                                else
                                {
                                    Console.WriteLine("texto no permitido");
                                    sw.WriteLine("texto no permitido");
                                }
                                //ingreso.Clear();
                                Thread.Sleep(500);
                            }
                        }
                        catch (Exception)
                        {
                            //Console.WriteLine($"no pueden ingresar datos en le id: {elementoID}");
                        }
                    }
                    //else if (elementoID.Type == "radio")
                    //{
                    //    Console.WriteLine("id: " + elementoID);
                    //    sw.WriteLine("id: " + elementoID);
                    //    var ingreso = chromeDriver.FindElementById(elementoID.Id);
                    //    Thread.Sleep(1000);
                    //    ingreso.Click();
                    //    if (ingreso.Selected)
                    //    {
                    //        Thread.Sleep(500);
                    //        sw.WriteLine($"En el id esta seleccionado");
                    //        Console.WriteLine($"En el id esta seleccionado");
                    //        sc.CaptureScreenToFile(direccionCapturas + elementoID.Id + "nombre" + formato, ImageFormat.Png);
                    //        //listaCapturas.Add(direccionCapturas + elementoID.Id + "nombre" + formato+".png");
                    //    }

                    //    else
                    //    {
                    //        Console.WriteLine("no permitido");
                    //        sw.WriteLine("no permitido");
                    //    }
                    //}
                }



                sw.Close();    //--------------------------------------------------------------------------------bloqueado tempotalmente
                               //foreach (var elementoName in listaName)
                               //{
                               //    Console.WriteLine("name: " + elementoName);
                               //}



                chromeDriver.Close();
                chromeDriver.Quit();
                return(listaCapturas);
            }
            catch (Exception e)
            {
                return(listaCapturas);
            }
        }