Ejemplo n.º 1
0
        public WebDriverFacade(IWebDriver web, Request request, ITakesScreenshot ss = null, IJavaScriptExecutor js = null)
        {
            _request = request;
            _web     = web;
            _ss      = ss ?? (ITakesScreenshot)web;
            _js      = js ?? (IJavaScriptExecutor)web;

            web.Manage().Timeouts().SetScriptTimeout(new TimeSpan(0, 5, 0));
        }
Ejemplo n.º 2
0
        public void Setup()
        {
            #region IWebDriver Setup
            IList<Cookie> cookies = new List<Cookie>();
            cookies.Add(new Cookie("s_cc","=true"));
            _web = Substitute.For<IWebDriver>();
            _web.Manage().Cookies.AllCookies.Returns(new ReadOnlyCollection<Cookie>(cookies));
            #endregion
            #region IJavascriptExecutor Setup
            IList<object> _dimensions = new List<object>(new object[] {800,600});
            var _dimensionsCollection = new ReadOnlyCollection<object>(_dimensions);
            _js = Substitute.For<IJavaScriptExecutor>();
            _js.ExecuteScript(Arg.Is(Javascript.Viewport)).Returns(_dimensionsCollection);
            IList<object> _browserInfo = new List<object>(new object[] { "firefox", "10.1", "WINDOWS" });
            var _browserInfoCollection = new ReadOnlyCollection<object>(_browserInfo);
            _js.ExecuteScript(Arg.Is(Javascript.Info)).Returns(_browserInfoCollection);
            IList<object> _resources = new List<object>(new[]
            {
                new Resource
                {
                    Uri = "http://c.mfcreativedev.com/webparts/banner/Banner.js?v=c5589edb",
                    StatusCode = HttpStatusCode.OK,
                    StatusDescription = "OK",
                    Headers = new List<string>
                    {
                        "Content-Length:194",
                        "Cache-Control:public, must-revalidate",
                        "Content-Type:application/x-javascript",
                        "Date:Thu, 20 Sep 2012 17:15:03 GMT",
                        "ETag:JsJt380DknGc4kAEEn76og=="
                    }
                }
            });

            var _resourcesCollection = new ReadOnlyCollection<object>(_resources);
            _js.ExecuteScript(Arg.Is(Javascript.Resources)).Returns(_resourcesCollection);
            #endregion
            #region ITakesScreenshot Setup
            _ss = Substitute.For<ITakesScreenshot>();
            var bp = ImageUtil.ImageToBase64(new Bitmap(10, 10), ImageFormat.Png);
            _ss.GetScreenshot().Returns(new Screenshot(bp));
            #endregion
            _request = new Request
            {
                Url = "http://www.google.com/",
                Browser = "firefox"
            };
            _facade = new WebDriverFacade(_web,_request,_ss,_js);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Method to get screeenshots during automation execution.
        /// </summary>
        /// <param name="driver"> IWEbDriver</param>
        /// <returns></returns>
        public static String TakeScreenshot(IWebDriver driver)
        {
            ITakesScreenshot ssdriver          = driver as ITakesScreenshot;
            String           currentDateFolder = CommonFunctions.GetProjectPath() + "Screenshots\\" + Todaysdate;
            var testCaseName  = TestContext.CurrentContext.Test.MethodName;
            var testClassName = TestContext.CurrentContext.Test.ClassName.Substring(TestContext.CurrentContext.Test.ClassName.LastIndexOf(".") + 1);

            if (!Directory.Exists(currentDateFolder))
            {
                Directory.CreateDirectory(currentDateFolder);
            }
            string screenshotPath = currentDateFolder + "\\Automation Report_" + DateTime.Now.ToString("hh_mm_ss") + ".png";

            try
            {
                Screenshot screenshot = ssdriver.GetScreenshot();
                screenshot.SaveAsFile(screenshotPath, ScreenshotImageFormat.Png);
            }
            catch (Exception e)
            {
            }
            return(screenshotPath);
        }
        public void ShouldCaptureScreenshotOfPageWithTooLongY()
        {
            ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot;

            if (screenshotCapableDriver == null)
            {
                return;
            }

            driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_y_too_long.html");
            Screenshot screenshot = screenshotCapableDriver.GetScreenshot();

            HashSet <string> actualColors = ScanActualColors(screenshot,
                                                             /* stepX in pixels */ 5,
                                                             /* stepY in pixels */ 100);

            HashSet <string> expectedColors = GenerateExpectedColors(/* initial color */ 0x0F0F0F,
                                                                     /* color step*/ 1000,
                                                                     /* grid X size */ 6,
                                                                     /* grid Y size */ 6);

            CompareColors(expectedColors, actualColors);
        }
Ejemplo n.º 5
0
        public void CreatePdf_WOP(string orderno, string pdfName)
        {
            string          outputPath = "";
            MySqlConnection con        = new MySqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
            string          query      = "SELECT Storage_Path FROM state_county_master where State_Name = '" + GlobalClass.sname + "' and County_Name='" + GlobalClass.cname + "'";
            MySqlCommand    cmd        = new MySqlCommand(query, con);

            con.Open();
            MySqlDataReader dr = cmd.ExecuteReader();

            while (dr.Read())
            {
                outputPath = dr["Storage_Path"].ToString();
            }
            dr.Close();
            con.Close();
            outputPath = outputPath + orderno + "\\";
            if (!Directory.Exists(outputPath))
            {
                Directory.CreateDirectory(outputPath);
            }
            string img = outputPath + pdfName + ".png";
            string pdf = outputPath + pdfName + ".pdf";

            //  driver.Manage().Window.Maximize();
            //driver.TakeScreenshot().SaveAsFile(img, ScreenshotImageFormat.Png);
            ITakesScreenshot screenshotDriver = driver as ITakesScreenshot;
            Screenshot       screenshot       = screenshotDriver.GetScreenshot();

            screenshot.SaveAsFile(img, ScreenshotImageFormat.Png);

            WebDriverTest.ConvertImageToPdf(img, pdf);
            if (File.Exists(img))
            {
                File.Delete(img);
            }
        }
Ejemplo n.º 6
0
        public static void TakeScreenshotOnFailure()
        {
            if (ScenarioContext.Current.TestError != null)
            {
                try
                {
                    DateTime dateTime         = DateTime.Now;
                    String   featureTitle     = FeatureContext.Current.FeatureInfo.Title;
                    String   scenarioTitle    = ScenarioContext.Current.ScenarioInfo.Title;
                    String   failureImageName = dateTime.ToString("HH-mm-ss")
                                                + "_"
                                                + scenarioTitle
                                                + ".png";
                    String screenshotsDirectory = AppDomain.CurrentDomain.BaseDirectory
                                                  + "../../"
                                                  + "\\Project\\Screenshots\\"
                                                  + dateTime.ToString("dd-MM-yyyy")
                                                  + "\\";
                    if (!Directory.Exists(screenshotsDirectory))
                    {
                        Directory.CreateDirectory(screenshotsDirectory);
                    }

                    ITakesScreenshot screenshotHandler = webDriver as ITakesScreenshot;
                    Screenshot       screenshot        = screenshotHandler.GetScreenshot();
                    screenshotPath = Path.Combine(screenshotsDirectory, failureImageName);
                    screenshot.SaveAsFile(screenshotPath, ScreenshotImageFormat.Png);
                    Console.WriteLine(scenarioTitle
                                      + " -- Scenario failed and the screenshot is available at -- "
                                      + screenshotPath);
                }
                catch (Exception exception)
                {
                    Console.WriteLine("Exception occurred while taking screenshot - " + exception);
                }
            }
        }
Ejemplo n.º 7
0
        private void TakeScreenshot(IWebDriver driver)
        {
            try
            {
                string fileNameBase = string.Format("error_{0}_{1}_{2}",
                                                    FeatureContext.Current.FeatureInfo.Title.ToIdentifier(),
                                                    ScenarioContext.Current.ScenarioInfo.Title.ToIdentifier(),
                                                    DateTime.Now.ToString("yyyyMMdd_HHmmss"));

                var artifactDirectory = Path.Combine(Directory.GetCurrentDirectory(), "testresults");
                if (!Directory.Exists(artifactDirectory))
                {
                    Directory.CreateDirectory(artifactDirectory);
                }

                string pageSource     = driver.PageSource;
                string sourceFilePath = Path.Combine(artifactDirectory, fileNameBase + "_source.html");
                File.WriteAllText(sourceFilePath, pageSource, Encoding.UTF8);
                Console.WriteLine("Page source: {0}", new Uri(sourceFilePath));

                ITakesScreenshot takesScreenshot = driver as ITakesScreenshot;

                if (takesScreenshot != null)
                {
                    var screenshot = takesScreenshot.GetScreenshot();

                    string screenshotFilePath = Path.Combine(artifactDirectory, fileNameBase + "_screenshot.png");

                    screenshot.SaveAsFile(screenshotFilePath, format: ScreenshotImageFormat.Png);
                    Console.WriteLine("Screenshot: {0}", new Uri(screenshotFilePath));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error while taking screenshot: {0}", ex);
            }
        }
Ejemplo n.º 8
0
        public void TakeScreenshot(string featureContext, string scenarioContext)
        {
            try
            {
                scenarioContext = TruncateString(scenarioContext);
                string fileNameBase = string.Format("{0}_{1}",
                                                    scenarioContext,
                                                    DateTime.Now.ToString("yyMMdd_HHmmss"));
                fileNameBase = fileNameBase.Replace(' ', '_');
                //var resultFolder = Path.Combine(Directory.GetCurrentDirectory(), "AutomationTestResult");
                string resultFolder = Path.Combine(_driverPath, "AutomationTestResult");
                if (!Directory.Exists(resultFolder))
                {
                    Directory.CreateDirectory(resultFolder);
                }

                var baseDir = Path.Combine(resultFolder, featureContext, scenarioContext);
                if (!Directory.Exists(baseDir))
                {
                    Directory.CreateDirectory(baseDir);
                }

                ITakesScreenshot takesScreenshot = Driver as ITakesScreenshot;

                if (takesScreenshot != null)
                {
                    var    screenshot         = takesScreenshot.GetScreenshot();
                    string screenshotFilePath = Path.Combine(baseDir, fileNameBase + ".png");
                    //screenshot.SaveAsFile(screenshotFilePath, ImageFormat.Png);
                    Console.WriteLine("Screenshot: {0}", new Uri(screenshotFilePath));
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Unable to take screenshot" + ex);
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        ///  getScreenshot
        /// </summary>
        /// Purpose: Capture the screenshot and merge with Gallio Report
        /// <return>Bitmap</returns>

        public string getScreenshot(IWebDriver _driver)
        {
            try
            {
                string fileNameBase = string.Format("error_{0}_{1}",
                                                    ScenarioContext.Current.ScenarioInfo.Title.ToString(),
                                                    DateTime.Now.ToString("yyyyMMddHHmmss"));
                fileNameBase = new Regex(@"\s+").Replace(fileNameBase, "_");
                if (File.Exists(fileNameBase))
                {
                    File.Delete(fileNameBase);
                }

                string ScreenshotFolder = getScreenLocation();
                if (!Directory.Exists(ScreenshotFolder))
                {
                    Directory.CreateDirectory(ScreenshotFolder);
                }
                string           fileName         = Path.Combine(ScreenshotFolder, fileNameBase + ".png");
                ITakesScreenshot screenshotDriver = _driver as ITakesScreenshot;
                Screenshot       screenshot       = screenshotDriver.GetScreenshot();
                screenshot.SaveAsFile(fileName, ScreenshotImageFormat.Png);
                Console.WriteLine("Screenshot: {0}", new Uri(fileName));
                return("");
                // return new Bitmap((new MemoryStream(screenshot.AsByteArray)));
            }
            catch (ArgumentNullException e)
            {
                log.Error(e.Message);
                throw new Exception(e.Message);
            }
            catch (Exception e)
            {
                log.Error(e.Message);
                throw new Exception(" Unable  to  Take  screenshot  because  of  " + e.Message);
            }
        }
Ejemplo n.º 10
0
        public void ShouldCaptureScreenshotAtIFramePage()
        {
            ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot;

            if (screenshotCapableDriver == null)
            {
                return;
            }

            driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_iframes.html");

            // Resize the window to avoid scrollbars in screenshot
            Size originalSize = driver.Manage().Window.Size;

            driver.Manage().Window.Size = new Size(1040, 700);

            Screenshot screenshot = screenshotCapableDriver.GetScreenshot();

            driver.Manage().Window.Size = originalSize;

            HashSet <string> actualColors = ScanActualColors(screenshot,
                                                             /* stepX in pixels */ 5,
                                                             /* stepY in pixels */ 5);

            HashSet <string> expectedColors = GenerateExpectedColors(/* initial color */ 0x0F0F0F,
                                                                     /* color step*/ 1000,
                                                                     /* grid X size */ 6,
                                                                     /* grid Y size */ 6);

            expectedColors.UnionWith(GenerateExpectedColors(/* initial color */ 0xDFDFDF,
                                                            /* color step*/ 1000,
                                                            /* grid X size */ 6,
                                                            /* grid Y size */ 6));

            // expectation is that screenshot at page with Iframes will be taken for full page
            CompareColors(expectedColors, actualColors);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// capture screen with screen shot
        /// </summary>
        /// <returns></returns>
        public static string CaptureScreenWithCallStack()
        {
            try
            {
                if (BoolScreenShotOnException)
                {
                    screenShotPath = string.Empty;
                    screenShotPath = ConfigurationManager.AppSettings["ScreenShotPath"] + DateTime.Now.ToLongDateString();
                    string filename = DateTime.Now.ToString("HH:mm");

                    string CallStack = GetCallStack();
                    screenShotPath = screenShotPath + "\\\\" + "_" + CallStack + "_" + filename.Replace(":", "_") + ".png";
                    ITakesScreenshot ssdriver = Browser.driver as ITakesScreenshot;

                    OpenQA.Selenium.Screenshot screenshot = ssdriver.GetScreenshot();
                    screenshot.SaveAsFile(screenShotPath);
                    return(screenShotPath);
                }
                else
                {
                    return(string.Empty);
                }
            }
            catch (UnhandledAlertException ex)
            {
                AlertMessage Alert = new AlertMessage();
                Alert.CloseAlertBox();
                ITakesScreenshot           ssdriver   = Browser.driver as ITakesScreenshot;
                OpenQA.Selenium.Screenshot screenshot = ssdriver.GetScreenshot();
                screenshot.SaveAsFile(screenShotPath);
                return(screenShotPath);
            }
            catch (Exception e)
            {
                return(screenShotPath);
            }
        }
Ejemplo n.º 12
0
        public void AssignTeacherFunction()
        {
            ChromeDriver driver = new ChromeDriver();

            try
            {
                string url = "http://*****:*****@example.com");
                driver.FindElement(By.Id("Password")).SendKeys("Admin@123456");
                driver.FindElement(By.Id("btnLogin")).Click();

                driver.FindElement(By.PartialLinkText("UsersAdmin")).Click();
                driver.FindElement(By.PartialLinkText("Assign Teacher")).Click();

                driver.FindElement(By.Id("Email")).SendKeys("*****@*****.**");
                driver.FindElement(By.Id("Password")).SendKeys("Parola_1");
                driver.FindElement(By.Id("ConfirmPassword")).SendKeys("Parola_1");
                SelectElement selectElement = new SelectElement(driver.FindElement(By.Name("Laboratories")));
                selectElement.SelectByText("SA");
                driver.FindElement(By.Id("assignButton")).Click();
                driver.FindElement(By.XPath("//td[text()='*****@*****.**']"));
                driver.Close();
                driver.Dispose();
            }
            catch
            {
                ITakesScreenshot screenshotDriver = driver as ITakesScreenshot;
                Screenshot       screenshot       = screenshotDriver.GetScreenshot();
                screenshot.SaveAsFile("E:/GitHub/Software-Engineering/WebApplicationTestareSelenium/test.png", ScreenshotImageFormat.Png);
                driver.Quit();
            }
        }
        public void TakeScreenshotAfterStep()
        {
            if (ScenarioContext.Current.TestError != null)
            {
                try
                {
                    ITakesScreenshot takesScreenshot = driver as ITakesScreenshot;

                    if (takesScreenshot != null)
                    {
                        var screenshot = takesScreenshot.GetScreenshot();

                        string screenshotFilePath = Path.Combine(Directory.GetCurrentDirectory(), Path.GetFileNameWithoutExtension(Path.GetTempFileName())) + ".jpg";
                        screenshot.SaveAsFile(screenshotFilePath, ScreenshotImageFormat.Png);

                        Console.WriteLine("Screenshot: {0}", new Uri(screenshotFilePath));
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error while taking screenshot: {0}", ex);
                }
            }
        }
Ejemplo n.º 14
0
        public void TakeScreenshot(string outputFolder, string fileNameBase)
        {
            try
            {
                if (!Directory.Exists(outputFolder))
                {
                    Directory.CreateDirectory(outputFolder);
                }

                ITakesScreenshot captureScreenshot = _webDriver as ITakesScreenshot;

                if (captureScreenshot != null)
                {
                    var    screenshot         = captureScreenshot.GetScreenshot();
                    string screenshotFilePath = Path.Combine(outputFolder, fileNameBase + ".png");
                    screenshot.SaveAsFile(screenshotFilePath, ScreenshotImageFormat.Png);
                    Console.WriteLine("screenshot:{0}", new Uri(screenshotFilePath));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("error while capturing screenshot:{0}", ex);
            }
        }
Ejemplo n.º 15
0
        public static string takeScreenShot(IWebDriver driver)
        {
            DateTime         d          = new DateTime();
            Random           rand       = new Random();
            ITakesScreenshot screen     = (ITakesScreenshot)driver;
            Screenshot       screenshot = screen.GetScreenshot();

            string random = Guid.NewGuid().ToString("N");

            //currentFolder = "\\ImgID" + rand.Next(1, 1000);
            currentFolder = "\\ImgID" + random;
            string path        = System.Reflection.Assembly.GetCallingAssembly().CodeBase;
            string actualPath  = path.Substring(0, path.IndexOf("GCP_Automation"));
            string projectPath = new Uri(actualPath).LocalPath;
            string finalPath1  = projectPath + "GCP_Automation\\GCP_Automation\\Reports\\ErrorScreenshots" + currentFolder + ".png";
            string finalPath   = "ErrorScreenshots" + currentFolder + ".png";

            // System.IO.DirectoryInfo file = new System.IO.DirectoryInfo(currentFolder);//path.Substring(0, path.LastIndexOf("bin"))
            // currentFolder = file.FullName;
            //string localPath = new Uri(finalPath).LocalPath;
            screenshot.SaveAsFile(finalPath1, ScreenshotImageFormat.Png);
            screenshot.SaveAsFile(projectPath + "GCP_Automation\\GCP_Automation\\ErrorScreenshots" + currentFolder + ".png", ScreenshotImageFormat.Png);
            return(finalPath1);
        }
        public string TakeScreenshot(ITakesScreenshot driver, BrowserTestContext context, string name)
        {
            if (driver == null)
            {
                throw new ArgumentNullException(nameof(driver));
            }

            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException(nameof(name));
            }

            var screenshot       = driver.GetScreenshot();
            var screenshotFolder = GetScreenshotFolder(context);
            var screenshotPath   = Path.Combine(screenshotFolder, name + ".png");

            screenshot.SaveAsFile(screenshotPath);
            return(screenshotPath);
        }
Ejemplo n.º 17
0
        public void ChangePasswordFunctionForStudent()
        {
            ChromeDriver driver = new ChromeDriver();

            try
            {
                string url = "http://*****:*****@yahoo.com");
                driver.FindElement(By.Id("Password")).SendKeys("Parola_1");
                driver.FindElement(By.Id("btnLogin")).Click();

                driver.FindElement(By.PartialLinkText("Hello student!")).Click();
                driver.FindElement(By.PartialLinkText("Change your password")).Click();

                driver.FindElement(By.Id("OldPassword")).SendKeys("Parola_1");
                driver.FindElement(By.Id("NewPassword")).SendKeys("Parola_2");
                driver.FindElement(By.Id("ConfirmPassword")).SendKeys("Parola_2");
                driver.FindElement(By.Id("changePasswordButton")).Click();

                WebDriverWait wait = new WebDriverWait(driver, new TimeSpan(0, 0, 5));
                wait.Until(wt => wt.FindElement(By.ClassName("text-success")));
                driver.Close();
                driver.Dispose();
            }
            catch
            {
                ITakesScreenshot screenshotDriver = driver as ITakesScreenshot;
                Screenshot       screenshot       = screenshotDriver.GetScreenshot();
                screenshot.SaveAsFile("E:/GitHub/Software-Engineering/WebApplication1/test.png", ScreenshotImageFormat.Png);
                driver.Quit();
            }
        }
Ejemplo n.º 18
0
        public void ShouldTakeScreenshotsOfAnElement()
        {
#if NETCOREAPP3_1 || NETSTANDARD2_1 || NET5_0
            Assert.Ignore("Skipping test: this framework can not process colors.");
#endif

            driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen.html");
            IWebElement element = driver.FindElement(By.Id("cell11"));

            ITakesScreenshot screenshotCapableElement = element as ITakesScreenshot;
            if (screenshotCapableElement == null)
            {
                return;
            }

            Screenshot screenImage = screenshotCapableElement.GetScreenshot();
            byte[]     imageData   = screenImage.AsByteArray;
            Assert.That(imageData, Is.Not.Null);
            Assert.That(imageData.Length, Is.GreaterThan(0));

            Color  pixelColor       = GetPixelColor(screenImage, 1, 1);
            string pixelColorString = FormatColorToHex(pixelColor.ToArgb());
            Assert.AreEqual("#0f12f7", pixelColorString);
        }
Ejemplo n.º 19
0
        private static Bitmap ExtraireCaptcha(IWebDriver driver)
        {
            ITakesScreenshot ssdriver = driver as ITakesScreenshot;
            Screenshot screenshot = ssdriver.GetScreenshot();

            Screenshot tempImage = screenshot;

            tempImage.SaveAsFile("full.png", ScreenshotImageFormat.Png);
            Wait(2);

            //replace with the XPath of the image element
            IWebElement my_image = driver.FindElement(By.XPath("//div[@id='captcha']/img[1]"));

            Point point = my_image.Location;
            int width = my_image.Size.Width;
            int height = my_image.Size.Height;

            Rectangle section = new Rectangle(point, new Size(width, height));
            Bitmap source = new Bitmap("full.png");
            source = SupprimerTraits(source);
            Bitmap final_image = CropImage(source, section);

            return final_image;
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Tira um print da página atual e salva no arquivo especificado
        /// </summary>
        /// <param name="nomeArquivo">Nome do arquivo</param>
        /// <param name="filePath">Diretório onde a imagem será salva</param>
        /// <param name="format">Formato da imagem salva</param>
        public void TakeScreeshot(string nomeArquivo, string filePath, ScreenshotImageFormat format)
        {
            try
            {
                if (string.IsNullOrEmpty(filePath))
                {
                    throw new ArgumentException("É necessário informar um diretório onde o arquivo será salvo.");
                }

                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }

                ITakesScreenshot screenshot = Driver as ITakesScreenshot;
                Screenshot       shot       = screenshot.GetScreenshot();

                shot.SaveAsFile(ScreenShotHelper.FormatFileName(nomeArquivo, filePath, format), format);
            }
            catch (WebDriverException e)
            {
                throw new WebDriverException(e.Message.ToString());
            }
        }
Ejemplo n.º 21
0
        public static string Capture(IWebDriver driver, string screenShotName)
        {
            string fileName = screenShotName + DateTime.UtcNow.ToString("yyyy-MM-dd-mm-ss") + ".Png";
            string path     = Environment.CurrentDirectory;

            var filePath = Path.GetFullPath(ApplicationDebugFolder);

            LatestResultReportFolder = Path.Combine(path, filePath, fileName);

            ITakesScreenshot ts         = (ITakesScreenshot)driver;
            Screenshot       screenshot = ts.GetScreenshot();
            //string path = System.Reflection.Assembly.GetCallingAssembly().CodeBase;
            //var dir = TestContext.CurrentContext.TestDirectory + "TestReport\\";
            // string finalpath = path.Substring(0, path.LastIndexOf("bin")) + "\\ErrorScreenshots\\" + screenShotName + DateTime.UtcNow.ToString("yyyy-MM-dd-mm-ss") +
            //".Png";


            string localpath = new Uri(LatestResultReportFolder).LocalPath;


            screenshot.SaveAsFile(localpath, ScreenshotImageFormat.Png);
            //var mediaModel = MediaEntityBuilder.
            return(localpath);
        }
Ejemplo n.º 22
0
 public void Test1(String urlName)
 {
     try
     {
         //driver.Url = "https://www.facebook.com/";
         driver.Url = urlName;
         IWebElement email = driver.FindElement(By.Id("email"));
     }
     catch (Exception e)
     {
         ITakesScreenshot ts         = driver as ITakesScreenshot;
         Screenshot       screenshot = ts.GetScreenshot();
         screenshot.SaveAsFile("C:\\Users\\JUDYANNGONZALES\\Desktop\\Projects\\SeleniumCSharp\\SeleniumCSharpProject\\Report\\Screenshots\\s1.jpeg", ScreenshotImageFormat.Jpeg);
         Console.WriteLine(e.StackTrace);
         throw;
     }
     finally
     {
         if (driver != null)
         {
             driver.Quit();
         }
     }
 }
Ejemplo n.º 23
0
        public static string GetScreenShot(IWebDriver driver, string screenShotName)
        {
            string path   = "C:\\AutomationErrorScreenshots\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            bool   exists = Directory.Exists(path);

            if (!exists)
            {
                Directory.CreateDirectory(path);
            }

            try {
                ITakesScreenshot ts          = (ITakesScreenshot)driver;
                Screenshot       screenshots = ts.GetScreenshot();
                //string pth = System.Reflection.Assembly.GetCallingAssembly().CodeBase;
                //string finalpth = pth.Substring(0, pth.LastIndexOf("bin")) + "ErrorScreenshots\\" + screenShotName + ".png";
                string finalpth  = path + screenShotName + ".png";
                string localpath = new Uri(finalpth).LocalPath;
                screenshots.SaveAsFile(localpath, ScreenshotImageFormat.Png);
                return(localpath);
            }
            catch {
                return(null);
            }
        }
 public static void TakeScreenshot(this IWebDriver driver, string fileNameBase)
 {
     try
     {
         var artifactDirectory = Path.Combine("C:\\evidence\\screenshots", "testresults" + DateTime.Now.ToString("yyyyMMdd"));
         if (!Directory.Exists(artifactDirectory))
         {
             Directory.CreateDirectory(artifactDirectory);
         }
         ITakesScreenshot takesScreenshot = driver as ITakesScreenshot;
         if (takesScreenshot != null)
         {
             var    screenshot         = takesScreenshot.GetScreenshot();
             string screenshotFilePath = Path.Combine(artifactDirectory, fileNameBase + ".jpg");
             Console.WriteLine($"[Screen Shot Path] {screenshotFilePath}");
             var screenshotBase64 = screenshot.AsBase64EncodedString;
             SaveByteArrayAsImage(screenshotFilePath, screenshotBase64);
         }
     }
     catch (Exception ex)
     {
         Console.Error.WriteLine("[ERROR]: Error while taking screenshot: {0}", ex);
     }
 }
Ejemplo n.º 25
0
        public void TestComCPF_ReturnSucesso()
        {
            driver.Navigate().GoToUrl("http://localhost:57959/");
            driver.FindElement(By.Id("nome")).Click();
            driver.FindElement(By.Id("nome")).Clear();
            driver.FindElement(By.Id("nome")).SendKeys("Paulo");
            driver.FindElement(By.Id("Sobrenome")).Clear();
            driver.FindElement(By.Id("Sobrenome")).SendKeys("Pellizzari");
            new SelectElement(driver.FindElement(By.Id("sexo"))).SelectByText("M");
            new SelectElement(driver.FindElement(By.Id("sexo"))).SelectByText("F");
            new SelectElement(driver.FindElement(By.Id("sexo"))).SelectByText("M");
            driver.FindElement(By.Id("Telefone")).Click();
            driver.FindElement(By.Id("Telefone")).Clear();
            driver.FindElement(By.Id("Telefone")).SendKeys("16516516651");
            driver.FindElement(By.Id("CPF")).Clear();
            driver.FindElement(By.Id("CPF")).SendKeys("1231232131");
            driver.FindElement(By.Id("CEP")).Clear();
            driver.FindElement(By.Id("CEP")).SendKeys("5161651");
            driver.FindElement(By.Id("Endereco")).Clear();
            driver.FindElement(By.Id("Endereco")).SendKeys("Rau Xpto");
            driver.FindElement(By.Id("Cidade")).Clear();
            driver.FindElement(By.Id("Cidade")).SendKeys("Sao Paulo");
            driver.FindElement(By.Id("Cargo")).Clear();
            driver.FindElement(By.Id("Cargo")).SendKeys("Programador Senior");
            driver.FindElement(By.Id("nomeMae")).Clear();
            driver.FindElement(By.Id("nomeMae")).SendKeys("Joana");
            driver.FindElement(By.Id("btnEnviar")).Click();
            driver.FindElement(By.XPath("//html")).Click();

            ITakesScreenshot camera     = driver as ITakesScreenshot;
            Screenshot       screenshot = camera.GetScreenshot();

            screenshot.SaveAsFile($"{Guid.NewGuid()}.png");

            Assert.IsNotNull(driver.FindElement(By.XPath("//pre[contains(text(),'Sucesso')]")));
        }
Ejemplo n.º 26
0
        static void Zadanie2()
        {
            Console.WriteLine("1.	Открыть форму «Нашли предложение лучше?» на https://msk.tele2.ru/, заполнить ее и закрыть (не отправлять!)");
            MyMozila.Navigate().GoToUrl(UrlSite[0]);
            var wait = new WebDriverWait(MyMozila, TimeSpan.FromSeconds(10));

            wait.Until(ExpectedConditions.PresenceOfAllElementsLocatedBy(By.CssSelector("div[data-cartridge-type='EmptyElementWithClass']")));
            //сначало прокрутить страницу вниз
            var objGOTO            = MyMozila.FindElement(By.CssSelector("div[data-cartridge-type='EmptyElementWithClass']"));
            IJavaScriptExecutor je = (IJavaScriptExecutor)MyMozila;

            je.ExecuteScript("arguments[0].scrollIntoView(true);", objGOTO);
            try
            {
                wait.Until(ExpectedConditions.PresenceOfAllElementsLocatedBy(By.CssSelector("iframe[id^='fl']")));
            }
            catch (WebDriverTimeoutException)
            {
                //не всегда подгружается фрейм
                Console.WriteLine("Форма не загрузилась, попробуйте еще раз. Задание прервано.");
                return;
            }
            var objFrom = MyMozila.FindElement(By.CssSelector("iframe[id^='fl']"));

            MyMozila.SwitchTo().Frame(objFrom);
            wait.Until(ExpectedConditions.PresenceOfAllElementsLocatedBy(By.CssSelector("button")));
            var objBtn = MyMozila.FindElement(By.CssSelector("button"));

            objBtn.Click();
            //наконец заполним форму
            MyMozila.FindElement(By.CssSelector("#tel")).SendKeys("9604422077");
            MyMozila.FindElement(By.CssSelector("#name")).SendKeys("Иван");
            //закроем ее
            //wait.Until(ExpectedConditions.PresenceOfAllElementsLocatedBy(By.CssSelector("section[class~='login']")));
            var objA = MyMozila.FindElement(By.CssSelector("section[class~='login'] a:first-child"));

            //objA.Click(); // ПОЧУМУ ТАК НЕ РАБОТАЕТ? ((((((((((((((
            ((IJavaScriptExecutor)MyMozila).ExecuteScript("arguments[0].click();", objA);
            Thread.Sleep(2000);//убедится что выше все отработало
            Console.WriteLine(objA.GetAttribute("Выполненно"));

            Console.WriteLine("2.	Открыть форму «Нашли предложение лучше?», открыть в новых окнах ссылки «правила"+
                              "программы» и «обработка персональных данных», сделать скриншоты открытых страниц из кода и сохранить их" +
                              "так, чтобы они лежали в том же месте, где и скрипт");
            //дабы не повторять выше код, просто выведу форму еще раз
            //objBtn.Click(); // уже не пашет
            ((IJavaScriptExecutor)MyMozila).ExecuteScript("arguments[0].click();", objBtn);
            wait.Until(ExpectedConditions.ElementIsVisible(By.CssSelector("a[class=js-rules]")));
            //запонить ссылку на основное окно (вкладку)
            List <String> HomeHandel = MyMozila.WindowHandles.ToList();

            //открываем ссылы
            //MyMozila.FindElement(By.CssSelector("a[class=js-rules]")).Click();
            //MyMozila.FindElement(By.CssSelector("a[class=js-personal]")).Click();
            ((IJavaScriptExecutor)MyMozila).ExecuteScript("arguments[0].click();",
                                                          MyMozila.FindElement(By.CssSelector("a[class=js-rules]")));
            ((IJavaScriptExecutor)MyMozila).ExecuteScript("arguments[0].click();",
                                                          MyMozila.FindElement(By.CssSelector("a[class=js-personal]")));
            //делаем скриншоты
            Thread.Sleep(2000); // подождем пока создадутся окна.
            List <String> NewHandel = MyMozila.WindowHandles.ToList();

            Console.WriteLine("ОТкрыто всего окн - " + NewHandel.Count);
            NewHandel.Remove(HomeHandel[0]);// удалили Основную
            //Screenshot MyMozilaScrShot = ((ITakesScreenshot)MyMozila).GetScreenshot();
            ITakesScreenshot MyMozilaScrShotDriver = MyMozila as ITakesScreenshot;
            Screenshot       MyMozilaScrShot;

            //String PutFile;
            foreach (var itemHandel in NewHandel)
            {
                MyMozila.SwitchTo().Window(itemHandel);
                Thread.Sleep(2000);
                //делаю скрин
                MyMozilaScrShot = MyMozilaScrShotDriver.GetScreenshot();
                MyMozilaScrShot.SaveAsFile(Environment.CurrentDirectory + "\\screen_" + DateTime.Now.Ticks + ".png");
                MyMozila.Close();
            }
            MyMozila.SwitchTo().Window(HomeHandel[0]);
        }
Ejemplo n.º 27
0
 public static string ScreenCaptureAsBase64String(this IWebDriver driver)
 {
     ITakesScreenshot ts         = (ITakesScreenshot)driver;
     Screenshot       screenshot = ts.GetScreenshot(); return(screenshot.AsBase64EncodedString);
 }
Ejemplo n.º 28
0
 public static void SavePageImage(this ITakesScreenshot webDriver, string imagePath, ImageFormat imageFormat)
 {
     webDriver.GetScreenshot().SaveAsFile(imagePath, imageFormat);
 }
 public Screenshot GetScreenshot()
 {
     _screenShot = _myDriver as ITakesScreenshot;
     return(_screenShot.GetScreenshot());
 }
        public static void takeScreenShot(string dir, string fname, string stmp)
        {
            ITakesScreenshot scrFile = driver as ITakesScreenshot;

            scrFile.GetScreenshot().SaveAsFile(dir + fname + stmp, ScreenshotImageFormat.Jpeg);
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Take a screenshot of the page referenced by the IWebDriver. In this version of the
        /// TakeScreenshot() method we will test to see if the feature is enabled in the test
        /// configuration and also evaluate the log level selected for the TakeScreenshot.
        ///
        /// </summary>
        public void TakeScreenshot(string screenShotNamePrefix)
        {
            int maxPathFilenameLength = 100;

            try
            {
                // Test to see if the screenshot is enabled in the test configuration
                if (testConfiguration.GetScreenCaptureEnable())
                {
                    // The fully qualified file name must be less than 260 characters,
                    // and the directory name must be less than 248 characters.

                    if (screenShotNamePrefix.Length > maxPathFilenameLength)
                    {
                        screenShotNamePrefix = screenShotNamePrefix.Substring(0, maxPathFilenameLength);
                    }

                    // Create the filename
                    string fileNameBase = string.Format("error_{0}_{1}",
                                                        screenShotNamePrefix,
                                                        DateTime.Now.ToString("yyyyMMdd_HHmmss_ffffff"));

                    // We will save the file to the project folder
                    string projectPath = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..\\..\\"));

                    var artifactDirectory = Path.Combine(projectPath, "testresults");

                    if (!Directory.Exists(artifactDirectory))
                    {
                        Directory.CreateDirectory(artifactDirectory);
                    }

                    // Create the takesScreenshot object
                    ITakesScreenshot takesScreenshot = driver as ITakesScreenshot;

                    if (takesScreenshot != null)
                    {
                        // Get the screenshot
                        var screenshot = takesScreenshot.GetScreenshot();

                        // Create the file path
                        string screenshotFilePath = Path.Combine(artifactDirectory, fileNameBase + "_screenshot.png");

                        // Write the image to the file system
                        screenshot.SaveAsFile(screenshotFilePath);

                        // Write the image file path to the console. This will be used to build the
                        // test execution report
                        logger.Info("Screenshot: {0}", new Uri(screenshotFilePath));
                    }
                }
            }
            catch (UnhandledAlertException)
            {
                //TODO: do nothing for now....selenium doesn't support sceen shot when alter window pops up...we can implement to take a shot of entire page...
                logger.Warn("Alert window poped up. We are taking screen shot when therre is an alert for now. We implement to take screen shot for alert case later.");
            }
            catch (Exception ex)
            {
                throw new Exception("Error while taking screenshot: {0}", ex);
            }
        }
        public void setPesquisaLinkedin()
        {
            var     wb       = new XLWorkbook(@"D:\Planilha\dados.xlsx");
            var     planilha = wb.Worksheet(1);
            Actions action   = new Actions(driver);


            driver.FindElement(linkedin.loginComboBox).SendKeys(planilha.Cell("A" + 2).Value.ToString());
            driver.FindElement(linkedin.passWordComboBox).SendKeys(planilha.Cell("B" + 2).Value.ToString());
            driver.FindElement(linkedin.clickSignIN).Click();

            if (driver.Url == "https://www.linkedin.com/feed/")
            {
                System.Threading.Thread.Sleep(5000);
                driver.FindElement(linkedin.pesquisaPessoa).SendKeys(planilha.Cell("C" + 2).Value.ToString());
                driver.FindElement(linkedin.pesquisaPessoa).SendKeys(Keys.Enter);

                System.Threading.Thread.Sleep(3000);

                driver.FindElement(linkedin.clickConexoes).Click();

                WebDriverWait espera        = new WebDriverWait(driver, new TimeSpan(0, 0, 4));
                IWebElement   clickCheckBox = espera.Until(ExpectedConditions.ElementToBeClickable(driver.FindElement(linkedin.clickCheckBox)));
                clickCheckBox.Click();

                driver.FindElement(linkedin.clickAplicar).Click();

                System.Threading.Thread.Sleep(5000);

                IList <IWebElement> elementos = driver.FindElements(linkedin.listaElementosConectar);

                Console.Write("Elementos encontrados " + elementos.Count);

                var allOptions = elementos.Count;

                for (int i = 0; i < allOptions; i++)

                {
                    if (elementos[i].Displayed)

                    {
                        // Clica no botão conectar
                        driver.FindElement(linkedin.clickConectar).Click();

                        // Mapeia o modal após o clique no botão conectar
                        driver.FindElement(linkedin.mapearModal);

                        // Clica no botão enviar agora
                        driver.FindElement(linkedin.clickEnviarAgora).Click();

                        // Realiza o refresh da pagina
                        driver.Navigate().Refresh();

                        // Espera pagina carregar
                        System.Threading.Thread.Sleep(4000);
                    }

                    action.SendKeys(Keys.End);
                    action.SendKeys(Keys.Home);
                }


                // Realizar o print da tela
                ITakesScreenshot screenshotDriver = driver as ITakesScreenshot;
                Screenshot       screenshot       = screenshotDriver.GetScreenshot();
                String           fp = "D:\\Screen\\" + "_" + DateTime.Now.ToString("dd_MMMM_hh_mm_ss_tt") + ".png";
                screenshot.SaveAsFile(fp, OpenQA.Selenium.ScreenshotImageFormat.Png);
            }
            else if (driver.Url == "https://www.linkedin.com/checkpoint/lg/login?errorKey=unexpected_error")

            {
                driver.FindElement(linkedin.loginComboBoxSengundaOpcao).SendKeys(planilha.Cell("A" + 2).Value.ToString());
                driver.FindElement(linkedin.passWordComboBoxSegundaOpcao).SendKeys(planilha.Cell("B" + 2).Value.ToString());
                driver.FindElement(linkedin.clickSignINsegundaOpcao).Click();

                System.Threading.Thread.Sleep(5000);

                driver.FindElement(linkedin.pesquisaPessoa).SendKeys(planilha.Cell("C" + 2).Value.ToString());
                driver.FindElement(linkedin.pesquisaPessoa).SendKeys(Keys.Enter);

                System.Threading.Thread.Sleep(5000);

                driver.FindElement(linkedin.clickConexoes).Click();

                WebDriverWait espera        = new WebDriverWait(driver, new TimeSpan(0, 0, 4));
                IWebElement   clickCheckBox = espera.Until(ExpectedConditions.ElementToBeClickable(driver.FindElement(linkedin.clickCheckBox)));
                clickCheckBox.Click();

                driver.FindElement(linkedin.clickAplicar).Click();

                System.Threading.Thread.Sleep(5000);

                IList <IWebElement> elementos = driver.FindElements(linkedin.listaElementosConectar);

                Console.Write("Elementos encontrados " + elementos.Count);

                var allOptions = elementos.Count;

                for (int i = 0; i < allOptions; i++)

                {
                    if (elementos[i].Displayed)

                    {
                        // Clica no botão conectar
                        driver.FindElement(linkedin.clickConectar).Click();

                        // Mapeia o modal após o clique no botão conectar
                        driver.FindElement(linkedin.mapearModal);

                        // Clica no botão enviar agora
                        driver.FindElement(linkedin.clickEnviarAgora).Click();

                        // Realiza o refresh da pagina
                        driver.Navigate().Refresh();

                        // Espera pagina carregar
                        System.Threading.Thread.Sleep(4000);
                    }

                    action.SendKeys(Keys.End);
                    action.SendKeys(Keys.Home);
                }


                // Realizar o print da tela
                ITakesScreenshot screenshotDriver = driver as ITakesScreenshot;
                Screenshot       screenshot       = screenshotDriver.GetScreenshot();
                String           fp = "D:\\Screen\\" + "_" + DateTime.Now.ToString("dd_MMMM_hh_mm_ss_tt") + ".png";
                screenshot.SaveAsFile(fp, OpenQA.Selenium.ScreenshotImageFormat.Png);
            }
            else
            {
                driver.Quit();
            }
        }