Exemple #1
0
        public void SaveScreenshot(string name)
        {
            string fileName = $"{TestContext.CurrentContext.Test.FullName} - {screenshotNumber.ToString("D4")} {name}.jpeg";

            screenshotTaker?.GetScreenshot().SaveAsFile(Path.Combine(TestContext.CurrentContext.WorkDirectory, fileName), ScreenshotImageFormat.Jpeg);
            screenshotNumber++;
        }
        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);
        }
Exemple #3
0
        public static string Capture(string screenShotName)
        {
            var    localpath  = "";
            string reportPath = ReportingHelpers.reportpath();
            string timeNow    = DateTime.Now.ToLongTimeString().ToString().Replace(':', '_');
            //initialize the reportsetup
            DateTime         localDate  = DateTime.Now;
            ITakesScreenshot ts         = (ITakesScreenshot)driver;
            Screenshot       screenshot = ts.GetScreenshot();
            string           pth        = System.Reflection.Assembly.GetCallingAssembly().CodeBase;
            string           fileName   = TestContext.CurrentContext.Test.MethodName + screenShotName + DateTime.Now.Ticks + ".png";
            var sub_directorypath       = reportPath + "\\ErrorScreenshots\\";

            localpath = sub_directorypath + fileName;
            if (!Directory.Exists(sub_directorypath))
            {
                Directory.CreateDirectory(sub_directorypath);
            }
            Logger.log("localpath::" + localpath);
            screenshot.SaveAsFile(localpath, ScreenshotImageFormat.Png);
            return(localpath);
        }
        private string Capturescreenshot(IWebDriver driver, string screenShotName)
        {
            string localpath = "";

            try
            {
                Thread.Sleep(4000);
                ITakesScreenshot ts         = (ITakesScreenshot)driver;
                Screenshot       screenshot = ts.GetScreenshot();
                string           pth        = System.Reflection.Assembly.GetCallingAssembly().CodeBase;
                var           dir           = AppDomain.CurrentDomain.BaseDirectory.Replace("\\bin\\Debug", "");
                DirectoryInfo di            = Directory.CreateDirectory(dir + "\\ScreenPrints\\Defect_Screenshots\\");
                string        finalpth      = pth.Substring(0, pth.LastIndexOf("bin")) + "\\ScreenPrints\\Defect_Screenshots\\" + screenShotName + ".png";
                localpath = new Uri(finalpth).LocalPath;
                screenshot.SaveAsFile(localpath);
            }
            catch (Exception e)
            {
                throw (e);
            }
            return(localpath);
        }
        public static void TakeScreenshotReport(IWebDriver driver)
        {
            ITakesScreenshot screenshotDriver = driver as ITakesScreenshot;
            Screenshot       screenshot       = screenshotDriver.GetScreenshot();


            string currentDirectory    = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
            string screenshotDirectory = Path.Combine(currentDirectory, ConfigurationManager.AppSettings["ScreenshotsDirectory"]);


            //todo fix directory creation
            if (!Directory.Exists(screenshotDirectory))
            {
                Directory.CreateDirectory(screenshotDirectory);
            }

            string photoName      = string.Format("HoursReport_{0}.png", DateTime.Now.ToString("yyyy-MM-dd_HH_mm_ss"));
            string screenshotPath = Path.Combine(screenshotDirectory, photoName);


            screenshot.SaveAsFile(screenshotPath, ScreenshotImageFormat.Png);
        }
        public static void TakeScreenshotTimeTask(IWebDriver driver, string newTaskId)
        {
            ITakesScreenshot screenshotDriver = driver as ITakesScreenshot;
            Screenshot       screenshot       = screenshotDriver.GetScreenshot();


            string currentDirectory    = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
            string screenshotDirectory = Path.Combine(currentDirectory, ConfigurationManager.AppSettings["ScreenshotsDirectory"]);


            //todo fix directory creation
            if (!Directory.Exists(screenshotDirectory))
            {
                Directory.CreateDirectory(screenshotDirectory);
            }

            string photoName      = string.Format("TimeTask_{0}.png", newTaskId);
            string screenshotPath = Path.Combine(screenshotDirectory, photoName);


            screenshot.SaveAsFile(screenshotPath, ScreenshotImageFormat.Png);
        }
        public void ShouldCaptureScreenshotAtFramePage()
        {
            ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot;

            if (screenshotCapableDriver == null)
            {
                return;
            }

            driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_frames.html");
            WaitFor(FrameToBeAvailableAndSwitchedTo("frame1"), "Did not switch to frame1");
            WaitFor(ElementToBeVisibleWithId("content"), "Did not find visible element with id content");

            driver.SwitchTo().DefaultContent();
            WaitFor(FrameToBeAvailableAndSwitchedTo("frame2"), "Did not switch to frame2");
            WaitFor(ElementToBeVisibleWithId("content"), "Did not find visible element with id content");

            driver.SwitchTo().DefaultContent();
            WaitFor(TitleToBe("screen test"), "Title was not expected value");
            Screenshot screenshot = screenshotCapableDriver.GetScreenshot();

            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 frames will be taken for full page
            CompareColors(expectedColors, actualColors);
        }
        public void EditClub(string clubName, string clubAddress, int clubBudget, string clubDesc)
        {
            var clubID = 12;

            _driver = new ChromeDriver();
            _driver.Navigate().GoToUrl(_websiteUrl + $"Clubs/Edit/{clubID}");
            _driver.Manage().Timeouts().ImplicitWait.TotalSeconds.Equals(10);

            _driver.FindElement(By.Name("ClubName")).Clear();
            _driver.FindElement(By.Name("ClubName")).SendKeys(clubName);
            _driver.FindElement(By.Name("ClubAddress")).Clear();
            _driver.FindElement(By.Name("ClubAddress")).SendKeys(clubAddress);
            _driver.FindElement(By.Name("ClubBudget")).Clear();
            _driver.FindElement(By.Name("ClubBudget")).SendKeys(clubBudget.ToString());
            _driver.FindElement(By.Name("ClubDesc")).Clear();
            _driver.FindElement(By.Name("ClubDesc")).SendKeys(clubDesc);
            //_driver.FindElement(By.Id("group")).Clear();
            //_driver.FindElement(By.Id("group")).SendKeys(group.ToString());
            //_driver.FindElement(By.Id("tournament")).Clear();
            //_driver.FindElement(By.Id("tournament")).SendKeys(tournament.ToString());

            _driver.FindElement(By.Id("edit")).Click();

            // screenshoot
            ITakesScreenshot screenshotDriver = _driver as ITakesScreenshot;
            Screenshot       screenshot       = screenshotDriver.GetScreenshot();
            var fileName = $"{clubID} Change data";

            screenshot.SaveAsFile($"C:/AutoTest/{fileName}.png", ScreenshotImageFormat.Png);


            Assert.Contains(clubName, _driver.PageSource);
            Assert.Contains(clubAddress, _driver.PageSource);
            Assert.Contains(clubBudget.ToString(), _driver.PageSource);
            Assert.Contains(clubDesc, _driver.PageSource);
            //Assert.Contains(group.ToString(), _driver.PageSource);
            //Assert.Contains(tournament.ToString(), _driver.PageSource);
        }
Exemple #9
0
        public void TeacherEditFromDetailsFunction()
        {
            ChromeDriver driver = new ChromeDriver();

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

                driver.FindElement(By.LinkText("UsersAdmin")).Click();
                driver.FindElement(By.LinkText("Details")).Click();
                driver.FindElement(By.LinkText("Edit")).Click();

                driver.FindElement(By.Id("emailEdit")).SendKeys("*****@*****.**");
                var element       = driver.FindElement(By.Name("LaboratoriesAssign"));
                var selectElement = new SelectElement(element);
                selectElement.SelectByValue("SA");
                driver.FindElement(By.ClassName("btn btn-default")).Click();

                WebDriverWait wait = new WebDriverWait(driver, new TimeSpan(0, 0, 5));
                wait.Until(wt => wt.FindElement(By.LinkText("Details")));
                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();
            }
        }
Exemple #10
0
        public void EditTeacherFunction()
        {
            ChromeDriver driver = new ChromeDriver();

            try
            {
                string url     = "http://*****:*****@value='Save']";
                driver = new ChromeDriver();
                driver.Navigate().GoToUrl(url);
                driver.Manage().Window.Maximize();

                driver.FindElement(By.Id("Email")).SendKeys("*****@*****.**");
                driver.FindElement(By.Id("Password")).SendKeys("Admin@123456");
                driver.FindElement(By.Id("btnLogin")).Click();

                driver.FindElement(By.LinkText("UsersAdmin")).Click();
                driver.FindElement(By.LinkText("Edit")).Click();

                driver.FindElement(By.Id("Email")).Clear();
                driver.FindElement(By.Id("Email")).SendKeys("*****@*****.**");
                SelectElement selectElement = new SelectElement(driver.FindElement(By.Name("SelectedLaboratoryId")));
                selectElement.SelectByText("Micro");

                driver.FindElement(By.XPath(button2)).Click();
                driver.FindElement(By.XPath("//td[contains(.,'*****@*****.**')]"));

                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();
            }
        }
Exemple #11
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(@"C:\Users\u65557\Documents\Visual Studio 2015\Projects\BDDFramework\ConsoleApplication2", "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");
                    scenario.AddScreenCaptureFromPath(screenshotFilePath);
                    screenshot.SaveAsFile(screenshotFilePath, ScreenshotImageFormat.Png);

                    Console.WriteLine("Screenshot: {0}", new Uri(screenshotFilePath));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error while taking screenshot: {0}", ex);
            }
        }
        public static void TakeScreenshot(IWebDriver driver)
        {
            string PathTargetScreenshot = ConfigurationManager.AppSettings["FilePathScreenshot"];

            try
            {
                string fileNameBase = string.Format("Evidencias_{0}_{1}_{2}",
                                                    FeatureContext.Current.FeatureInfo.Title.ToIdentifier(),
                                                    ScenarioContext.Current.ScenarioInfo.Title.ToIdentifier(),
                                                    DateTime.Now.ToString("ddMMyyyy_HHmmss"));

                var artifactDirectory = Path.Combine(PathTargetScreenshot, "Evidencias");

                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");
                    ScreenshotFilePath = screenshotFilePath;
                    screenshot.SaveAsFile(screenshotFilePath, ScreenshotImageFormat.Png);

                    Console.WriteLine("Screenshot: {0}", new Uri(screenshotFilePath));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Erro ao ao efetuar o screenshot: {0}", ex);
            }
        }
        private void TirarScreenshot(IWebDriver Driver)
        {
            try
            {
                string fileNameBase = string.Format("error-{0}_{1}",
                                                    //FeatureContext.Current.FeatureInfo.Title.ToIdentifier(),
                                                    DateTime.Now.ToString("dd.MM.yyyy"),
                                                    ScenarioContext.Current.ScenarioInfo.Title.ToIdentifier());

                var artifactDirectory = Path.Combine(Directory.GetCurrentDirectory(), "imagens_error");
                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 tirarScreenshot = Driver as ITakesScreenshot;

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

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

                    screenshot.SaveAsFile(screenshotCaminhoArquivo, ScreenshotImageFormat.Png);

                    Console.WriteLine("ScreenShot: {0}", new Uri(screenshotCaminhoArquivo));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Erro ao tirar screenshot: {0}", ex);
            }
        }
Exemple #14
0
        public static void TakeScreenshot(IWebDriver driver)
        {
            try
            {
                string fileNameBase = string.Format("Evidencias_{0}_{1}_{2}",
                                                    FeatureContext.Current.FeatureInfo.Title.ToIdentifier(),
                                                    ScenarioContext.Current.ScenarioInfo.Title.ToIdentifier(),
                                                    DateTime.Now.ToString("ddMMyyyy_HHmmss"));

                //var artifactDirectory = (Directory.GetParent(System.Reflection.Assembly.GetExecutingAssembly().Location)).Parent.Parent.FullName + "\\Evidencias";
                //var artifactDirectory = Path.Combine(Directory.GetCurrentDirectory(), "Evidencias");
                var artifactDirectory = ("c:\\Teste");

                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, ScreenshotImageFormat.Png);

                    Console.WriteLine("Screenshot: {0}", new Uri(screenshotFilePath));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Erro ao ao efetuar o screenshot: {0}", ex);
            }
        }
        public static 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(), "ResultadoTestes");
                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);

                    Console.WriteLine("Screenshot: {0}", new Uri(screenshotFilePath));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error while taking screenshot: {0}", ex);
            }
        }
Exemple #16
0
        public void Test1(String urlName)
        {
            IWebDriver driver = null;

            try
            {
                ChromeOptions options = new ChromeOptions()
                {
                    BinaryLocation = @"C:\Program Files\Google\Chrome\Application\chrome.exe"
                };
                driver = new ChromeDriver(options);
                driver.Manage().Window.Maximize();
                // driver.Url = "https://www.facebook.com/";
                driver.Url = urlName;

                IWebElement cookiesAcceptation = driver.FindElement(By.XPath(".//*[@id='u_0_h']"));
                cookiesAcceptation.Click();

                //IWebElement emailTextField = driver.FindElement(By.XPath(".//*[@id='email']"));
                IWebElement emailTextField = driver.FindElement(By.XPath(".//*[@id='asdas']"));
                emailTextField.SendKeys("Selenium C#");
            }
            catch (Exception e)
            {
                ITakesScreenshot ts         = driver as ITakesScreenshot;
                Screenshot       screenshot = ts.GetScreenshot();
                screenshot.SaveAsFile("C:\\Users\\lukas\\OneDrive\\Pulpit\\SeleniumCSharpSessions\\SeleniumCSharp\\SeleniumCSharpTutorials\\Screenshots\\s1.jpg", ScreenshotImageFormat.Jpeg);
                Console.WriteLine(e.StackTrace);
                throw;
            }
            finally
            {
                if (driver != null)
                {
                    driver.Quit();
                }
            }
        }
        public void ShouldCaptureScreenshotOfCurrentViewport()
        {
            ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot;

            if (screenshotCapableDriver == null)
            {
                return;
            }

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

            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);

            CompareColors(expectedColors, actualColors);
        }
        public void ShouldTakeScreenshotsOfAnElement()
        {
            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);
        }
Exemple #19
0
        /// <summary>
        /// Encerra o Driver e fecha o browser
        /// </summary>
        public void Quit()
        {
            try
            {
                Driver.Quit();
            }
            catch (Exception)
            {
                string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

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

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

                shot.SaveAsFile($@"{folderPath}\Reports\Error", ScreenshotImageFormat.Jpeg);

                Driver.Quit();
            }
        }
Exemple #20
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);
        }
Exemple #21
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);
        }
Exemple #22
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);
            }
        }
Exemple #23
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);
            }
        }
Exemple #24
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);
            }
        }
Exemple #25
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);
            }
        }
Exemple #26
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);
                }
            }
        }
Exemple #27
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);
        }
        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);
                }
            }
        }
Exemple #30
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);
     }
 }