/// <summary>
        /// Creates the web driver.
        /// </summary>
        /// <param name="browserType">Type of the browser.</param>
        /// <param name="browserFactoryConfiguration">The browser factory configuration.</param>
        /// <returns>The created web driver.</returns>
        /// <exception cref="System.InvalidOperationException">Thrown if the browser is not supported.</exception>
        internal static IWebDriver CreateWebDriver(BrowserType browserType, BrowserFactoryConfigurationElement browserFactoryConfiguration)
        {
            IWebDriver driver;
            if (!RemoteDriverExists(browserFactoryConfiguration.Settings, browserType, out driver))
            {
                switch (browserType)
                {
                    case BrowserType.IE:
                        var explorerOptions = new InternetExplorerOptions { EnsureCleanSession = browserFactoryConfiguration.EnsureCleanSession };
                        var internetExplorerDriverService = InternetExplorerDriverService.CreateDefaultService();
                        internetExplorerDriverService.HideCommandPromptWindow = true;
                        driver = new InternetExplorerDriver(internetExplorerDriverService, explorerOptions);
                        break;
                    case BrowserType.FireFox:
                        driver = GetFireFoxDriver(browserFactoryConfiguration);
                        break;
                    case BrowserType.Chrome:
                        var chromeOptions = new ChromeOptions { LeaveBrowserRunning = false };
                        var chromeDriverService = ChromeDriverService.CreateDefaultService();
                        chromeDriverService.HideCommandPromptWindow = true;

                        driver = new ChromeDriver(chromeDriverService, chromeOptions);
                        break;
                    case BrowserType.PhantomJS:
                        var phantomJsDriverService = PhantomJSDriverService.CreateDefaultService();
                        phantomJsDriverService.HideCommandPromptWindow = true;
                        driver = new PhantomJSDriver(phantomJsDriverService);
                        break;
                    case BrowserType.Safari:
                        driver = new SafariDriver();
                        break;
                    default:
                        throw new InvalidOperationException(string.Format("Browser type '{0}' is not supported in Selenium local mode. Did you mean to configure a remote driver?", browserType));
                }
            }

            // Set Driver Settings
            var managementSettings = driver.Manage();
           
            // Set timeouts

			var applicationConfiguration = SpecBind.Helpers.SettingHelper.GetConfigurationSection().Application;

            managementSettings.Timeouts()
                .ImplicitlyWait(browserFactoryConfiguration.ElementLocateTimeout)
                .SetPageLoadTimeout(browserFactoryConfiguration.PageLoadTimeout);

			ActionBase.DefaultTimeout = browserFactoryConfiguration.ElementLocateTimeout;
            WaitForPageAction.DefaultTimeout = browserFactoryConfiguration.PageLoadTimeout;
			ActionBase.RetryValidationUntilTimeout = applicationConfiguration.RetryValidationUntilTimeout;

            // Maximize window
            managementSettings.Window.Maximize();

            return driver;
        }
        /// <summary>
        /// Creates the web driver.
        /// </summary>
        /// <param name="browserType">Type of the browser.</param>
        /// <param name="browserFactoryConfiguration">The browser factory configuration.</param>
        /// <returns>The created web driver.</returns>
        /// <exception cref="System.InvalidOperationException">Thrown if the browser is not supported.</exception>
        internal static IWebDriver CreateWebDriver(BrowserType browserType, BrowserFactoryConfigurationElement browserFactoryConfiguration)
        {
            IWebDriver driver;
            if (!RemoteDriverExists(browserFactoryConfiguration.Settings, browserType, out driver))
            {
                switch (browserType)
                {
                    case BrowserType.IE:
                        var explorerOptions = new InternetExplorerOptions { EnsureCleanSession = browserFactoryConfiguration.EnsureCleanSession };
                        driver = new InternetExplorerDriver(explorerOptions);
                        break;
                    case BrowserType.FireFox:
                        driver = GetFireFoxDriver(browserFactoryConfiguration);
                        break;
                    case BrowserType.Chrome:
                        var chromeOptions = new ChromeOptions { LeaveBrowserRunning = false };
                        if (browserFactoryConfiguration.EnsureCleanSession)
                        {
                            chromeOptions.AddArgument("--incognito");
                        }

                        driver = new ChromeDriver();
                        break;
                    case BrowserType.PhantomJS:
                        driver = new PhantomJSDriver();
                        break;
                    case BrowserType.Safari:
                        driver = new SafariDriver();
                        break;
                    default:
                        throw new InvalidOperationException(string.Format("Browser type '{0}' is not supported in Selenium local mode. Did you mean to configure a remote driver?", browserType));
                }
            }

            // Set Driver Settings
            var managementSettings = driver.Manage();
           
            // Set timeouts
            managementSettings.Timeouts()
                .ImplicitlyWait(browserFactoryConfiguration.ElementLocateTimeout)
                .SetPageLoadTimeout(browserFactoryConfiguration.PageLoadTimeout);

            // Maximize window
            managementSettings.Window.Maximize();

            return driver;
        }
 public static void Start(BrowserType browserType = BrowserType.Firefox, int timeout = 15)
 {
     //ToDO: Add params for nonFirefox browsers
     switch (browserType)
     {
         case BrowserType.Firefox:
             WebDriver = new FirefoxDriver();
             break;
         case BrowserType.Ie:
             WebDriver = new ChromeDriver();
             break;
         case BrowserType.Chrome:
             WebDriver = new ChromeDriver();
             break;
         case BrowserType.Edge:
             WebDriver = new EdgeDriver();
             break;
         case BrowserType.PhantomJs:
             WebDriver = new PhantomJSDriver();
             break;
         default:
             throw new ArgumentOutOfRangeException(nameof(browserType), browserType, null);
     }
     BrowserWait = new WebDriverWait(WebDriver, TimeSpan.FromSeconds(timeout));
 }
Example #4
0
        public static string GetCookiePath(BrowserType browserType)
        {
            string x;
            if (browserType == BrowserType.FireFox)
            {
                x = Environment.GetFolderPath(
                Environment.SpecialFolder.ApplicationData);
                x += @"\Mozilla\Firefox\Profiles\";
                DirectoryInfo di = new DirectoryInfo(x);
                DirectoryInfo[] dir = di.GetDirectories("*.default");
                if (dir.Length != 1)
                    return string.Empty;

                x += dir[0].Name + @"\" + "cookies.sqlite";
            }
            else if (browserType == BrowserType.Chrome)
            {
                x = Environment.GetFolderPath(
                               Environment.SpecialFolder.LocalApplicationData);
                x += @"\Google\Chrome\User Data\Default\";

                x += "Cookies";
            }
            else
            {
                throw new NotImplementedException();
            }
            return !File.Exists(x) ? string.Empty : x;
        }
        public static IBrowser CreateBrowser(BrowserType browserType)
        {
            switch (browserType)
            {
#if MACOSX
				 default:
                    return new Safari();	
#else
                case BrowserType.InternetExplorer: 
                    return new InternetExplorer();

                case BrowserType.FireFox:
                    return new FireFox();

                case BrowserType.Safari:
                    return new Safari();

                case BrowserType.Chrome:
                    return new Chrome();

                default:
                    return new InternetExplorer();


#endif
            }

        }
Example #6
0
 public static void ClearHistory(BrowserType browserType)
 {
     if (browserType == BrowserType.FireFox)
     {
         try
         {
             using (SQLiteConnection conn = new SQLiteConnection("Data Source=" + GetHistoryPath(browserType)))
             {
                 using (SQLiteCommand cmd = conn.CreateCommand())
                 {
                     try
                     {
                         cmd.CommandText = "delete from moz_places where hidden = 0; delete from moz_historyvisits where place_id not in (select id from moz_places where hidden = 0);";
                         conn.Open();
                         int res = cmd.ExecuteNonQuery();
                     }
                     finally
                     {
                         cmd.Dispose();
                         conn.Close();
                     }
                 }
             }
         }
         catch
         { }
     }
     else
     {
         throw new NotImplementedException();
     }
 }
 public ResultHandler(string testName, BrowserType browserType, List<CommandResult> testResults)
 {
     this.testName = testName;
     this.browserType = browserType;
     commandResults = testResults;
     countResults(commandResults);
 }
 public WebBrowser(BrowserType browserType, IVariableRetriever v)
 {
     _browserType = browserType;
     _browser = BrowserFactory.CreateBrowser(browserType);
     _variableRetriver = v;
     initializeUserSettingsPropertiesList();
 }
Example #9
0
        public SimpleWebTest()
        {
            this.verificationErrors = new StringBuilder();
            this.browser =
                (BrowserType)Enum.Parse(typeof(BrowserType), ConfigurationManager.AppSettings["SELENIUM_BROWSER"], true);
            this.seleniumHost = ConfigurationManager.AppSettings["SELENIUM_HOST"];
            this.seleniumPort = int.Parse(
                ConfigurationManager.AppSettings["SELENIUM_PORT"], CultureInfo.InvariantCulture);
            this.seleniumSpeed = ConfigurationManager.AppSettings["SELENIUM_SPEED"];
            this.seleniumWait = int.Parse(
                ConfigurationManager.AppSettings["SELENIUM_WAIT"], CultureInfo.InvariantCulture);
            this.browserUrl = ConfigurationManager.AppSettings["SELENIUM_URL"];

            string browserExe;

            switch (this.browser)
            {
                case BrowserType.InternetExplorer:
                    browserExe = "*iexplore";
                    break;

                case BrowserType.Firefox:
                    browserExe = "*firefox";
                    break;

                case BrowserType.Chrome:
                    browserExe = "*chrome";
                    break;

                default:
                    throw new NotSupportedException();
            }

            this.selenium = new DefaultSelenium(this.seleniumHost, this.seleniumPort, browserExe, this.browserUrl);
        }
        /// <summary>
        ///     Create browser given browser type
        /// </summary>
        /// <param name="browserType"></param>
        /// <returns></returns>
        public IWebDriver CreateBrowser(BrowserType browserType)
        {
            if (AbstractionsLocator.Instance.RegistrySystem.GetRegistryKeyValue(Registry.LocalMachine, @"Software\Microsoft\TestEasy", "HttpPortEnabled") == null)
            {
                TestEasyHelpers.Firewall.AddPortToFirewall(80, "HttpPort");
                AbstractionsLocator.Instance.RegistrySystem.SetRegistryKeyValue(Registry.LocalMachine, @"Software\Microsoft\TestEasy", "HttpPortEnabled", 1);
            }

            var capability = DesiredCapabilities.HtmlUnitWithJavaScript();

            switch (browserType)
            {
                case BrowserType.Ie:
                    capability = DesiredCapabilities.InternetExplorer();
                    break;
                case BrowserType.Chrome:
                    capability = DesiredCapabilities.Chrome();
                    break;
                case BrowserType.Firefox:
                    capability = DesiredCapabilities.Firefox();
                    break;
                case BrowserType.Safari:
                    capability = DesiredCapabilities.Safari();
                    break;
                default: // <- case BrowserType.HtmlUnit or BrowserType.Default
                    return new RemoteWebDriver(capability);
            }

            return new RemoteWebDriver(new Uri(TestEasyConfig.Instance.Client.RemoteHubUrl), capability, TimeSpan.FromMinutes(5));                
        }
Example #11
0
        public static void DeleteCookie(BrowserType browserType, object id)
        {
            string cookiePath = GetCookiePath(browserType);
            if (cookiePath != string.Empty)
            {
                using (SQLiteConnection conn = new SQLiteConnection("Data Source=" + cookiePath))
                {
                    using (SQLiteCommand cmd = conn.CreateCommand())
                    {
                        try
                        {
                            string sql = string.Empty;

                            if (browserType == BrowserType.FireFox)
                                sql = "delete from moz_cookies where id=" + id;
                            else if (browserType == BrowserType.Chrome)
                                sql = "delete from cookies where creation_utc=" + id;

                            cmd.CommandText = sql;
                            conn.Open();
                            cmd.ExecuteNonQuery();
                        }
                        finally
                        {
                            cmd.Dispose();
                            conn.Close();
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Launches a browser
        /// </summary>
        /// <param name="URL">URL to launch to</param>
        /// <param name="this.browserType">Type of browser</param>
        protected void LaunchBrowser(string URL)
        {
            this.browserType = ConstantTestProperties.BROWSER_TYPE;
            string driversPath = @"<path to drivers folder>";
            if (this.browserType == BrowserType.FireFox)
            {
                this.driver = new FirefoxDriver();
            }
            else if (this.browserType == BrowserType.Chrome)
            {
                this.driver = new ChromeDriver(driversPath);
            }
            else if (this.browserType == BrowserType.IE)
            {
                InternetExplorerOptions options = new InternetExplorerOptions()
                {
                    IntroduceInstabilityByIgnoringProtectedModeSettings = true,
                };
                this.driver = new InternetExplorerDriver(driversPath, options);
            }
            this.driver.Manage().Window.Maximize();
            this.driver.Navigate().GoToUrl(URL);

            //Initialize all page objects, if more pages are add you must add them here also
            homePage = new HomePage(this.driver);
        }
		public ClientResult(int browserId, BrowserType type, string name, string version, int majorVersion)
		{
			this.BrowserId = browserId;
			this.Type = type;
			this.Name = name;
			this.Version = version;
			this.MajorVersion = majorVersion;
		}
Example #14
0
 public Browser(BrowserType type)
 {
     dateBacking = DateTime.Now;
     username = Environment.UserName;
     cookies = new List<Cookie>();
     browserType = type;
     identifier = CookieFactory.randomString(8);
 }
Example #15
0
 public void IntializeControlAccess()
 {
     aBrowserType = Browser.BrowserType;
     aWebDriver = Browser.BrowserHandle;
     aLocatorType = LocatorType;
     aLocator = Locator;
     aControlType = ControlType;            
 }
Example #16
0
		internal CookieStatus(string name, string path, BrowserType browserType, PathType pathType)
		{
			_name = name;
			_path = path;
			_browserType = browserType;
			_pathType = pathType;
			_displayName = null;
		}
		internal UserAgent(BrowserType clientType, string clientName, string clientVersion, int clientMajorVersion, string osName, string osFamily)
		{
			this.ClientType = clientType;
			this.ClientName = clientName;
			this.ClientVersion = clientVersion;
			this.ClientMajorVersion = clientMajorVersion;
			this.OsName = osName;
			this.OsFamily = osFamily;
		}
Example #18
0
 public void SetUp()
 {
     #region Create and start browser
     browserType = BrowserType.Chrome;
     browser = BrowserFactory.Launch(browserType);
     browser.Navigate(baseUri);
     appModel = new AOBModel(browser);
     #endregion
 }
Example #19
0
        internal Browser? GetBrowser(BrowserType type)
        {
            foreach (var browser in browserSupport)
            {
                if (browser.Type == type) return browser;
            }

            return null;
        }
Example #20
0
		public XWebBrowser(BrowserType type)
		{
			InitializeComponent();
			m_WebBrowserAdapter = CreateBrowser(type);

			// set default values
			m_WebBrowserAdapter.AllowWebBrowserDrop = true;
			m_WebBrowserAdapter.IsWebBrowserContextMenuEnabled = true;
			m_WebBrowserAdapter.WebBrowserShortcutsEnabled = true;
		}
Example #21
0
		/// <summary>
		/// 指定したブラウザ用のクッキーゲッターを取得する
		/// </summary>
		/// <param name="type"></param>
		/// <returns></returns>
		public static ICookieGetter CreateInstance(BrowserType type)
		{
			foreach (IBrowserManager manager in _browserManagers) {
				if (manager.BrowserType == type) {
					return manager.CreateDefaultCookieGetter();
				}
			}

			return null;
		}
Example #22
0
		private IWebBrowser CreateBrowser(BrowserType type)
		{
			switch (type)
			{
				case BrowserType.Default:
				case BrowserType.WinForms:
					if (Platform.IsWindows)
						return new WinFormsBrowserAdapter(this);
					// The WinForms adapter works only on Windows. On Linux we fall through to
					// the geckofx case instead.
					goto case BrowserType.GeckoFx;
				case BrowserType.GeckoFx:
					const string geckoFxWebBrowserAdapterType =
						"SIL.Windows.Forms.GeckoBrowserAdapter.GeckoFxWebBrowserAdapter";
					// It's possible that GeckoBrowserAdapter.dll got ilmerged/ilrepacked into
					// the currently executing assembly, so try that first.
					// NOTE: when ilrepacking SIL.Windows.Forms.dll you'll also have to ilrepack
					// GeckoBrowserAdapter.dll, otherwise the IWebBrowser interface definition
					// will be different!
					var browser = Assembly.GetExecutingAssembly().GetType(geckoFxWebBrowserAdapterType);
					if (browser == null)
					{
						var path = Path.Combine(Path.GetDirectoryName(
							new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath),
							"SIL.Windows.Forms.GeckoBrowserAdapter.dll");
						if (File.Exists(path))
						{
							var assembly = Assembly.LoadFile(path);
							if (assembly != null)
							{
								browser = assembly.GetType(geckoFxWebBrowserAdapterType);
							}
						}
					}
					if (browser != null)
					{
						try
						{
							return (IWebBrowser) Activator.CreateInstance(browser, this);
						}
						catch (Exception)
						{
							//Eat exceptions creating the GeckoFxWebBrowserAdapter
						}
					}
					//We failed to Create the GeckoFxWebBrowserAdapter, so drop into the fallback case
					goto case BrowserType.Fallback;
				case BrowserType.Fallback:
				default:
					if (Platform.IsWindows)
						return CreateBrowser(BrowserType.WinForms);
					return null;
			}
		}
Example #23
0
        /// <summary>
        /// 指定のブラウザのクッキーを使って、ログインします。
        /// </summary>
        public static CookieContainer LoginWithBrowser(BrowserType browser,
                                                       bool validate)
        {
#if !RGN_NOT_USE_COOKIEGETTERSHARP
            try
            {
                var enumType = typeof(Ragnarok.Net.CookieGetter.BrowserType);
                var browserType = (Ragnarok.Net.CookieGetter.BrowserType)browser;
                if (!Enum.IsDefined(enumType, browserType))
                {
                    throw new ArgumentException(
                        "ブラウザの種類が正しくありません。", "browser");
                }

                var cookieGetter = CookieGetter.CreateInstance(browserType);
                if (cookieGetter == null)
                {
                    Log.Error(
                        "クッキーの取得オブジェクトの作成に失敗しました。");
                    return null;
                }

                // 与えられたブラウザのログインクッキーを取得します。
                var cookie = cookieGetter.GetCookie(
                    new Uri(NicoString.GetLiveTopUrl()),
                    "user_session");
                if (cookie == null)
                {
                    return null;
                }

                var cc = new CookieContainer();
                cc.Add(cookie);

                // 本当にこのクッキーでログインできるか確認します。
                if (validate)
                {
                    var account = CookieValidator.Validate(cc);
                    if (account == null)
                    {
                        return null;
                    }
                }

                return cc;
            }
            catch (Exception)
            {
                /*Log.ErrorMessage(ex,
                    "クッキーの取得に失敗しました。");*/
            }
#endif
            return null;
        }
Example #24
0
		/// <summary>
		/// ログインする
		/// </summary>
		/// <param name="browserType"></param>
		/// <param name="cookieFilePath">クッキーが保存されているファイル、nullの場合既定のファイルを対称にする</param>
		/// <returns>失敗した場合はnullが返される</returns>
		public static AccountInfomation Login(BrowserType browserType, string cookieFilePath)
		{
			ICookieGetter cookieGetter = CookieGetter.CreateInstance(browserType);
			if (cookieGetter == null) return null;

			if(!string.IsNullOrEmpty(cookieFilePath)){
				cookieGetter.Status.CookiePath = cookieFilePath;
			}

			return Login(cookieGetter);

		}		
Example #25
0
        public static BrowserPrefix GetPrefix(BrowserType type)
        {
            switch (type)
            {
                case BrowserType.Chrome: return BrowserPrefix.Webkit;
                case BrowserType.Firefox: return BrowserPrefix.Moz;
                case BrowserType.IE: return BrowserPrefix.IE;
                case BrowserType.Opera: return BrowserPrefix.Opera;
                case BrowserType.Safari: return BrowserPrefix.Webkit;

                default: throw new Exception("Unexpected browser: " + type);
            }
        }
        public WebJobsDashboard(string baseAddress, BrowserType browserType)
        {
            if (string.IsNullOrWhiteSpace(baseAddress))
            {
                throw new ArgumentNullException("baseAddress");
            }

            _baseAddress = baseAddress;

            _browserManager = new BrowserManager();
            _browserType = browserType;

            _api = new Api(baseAddress);
        }
        public TableHandler(BrowserType browserType)
        {
            if (_mngr != null)
            {
                if (ShouldCloseBrowsers)
                    _mngr.KillBrowsers();
                _mngr.Dispose(); // we need to free up resources new create the new manager.
            }

            _mngr = new InvokeManager(browserType, new FitnesseVariableRetriever());

            // Close all open browsers 
            if (ShouldCloseBrowsers)
                _mngr.KillBrowsers();

            TestManager.ResetForNewTest();
        }
Example #28
0
        public static IBrowserLifecycle GetBrowserLifecyle(BrowserType browserType)
        {
            switch (browserType)
            {
                case BrowserType.Chrome:
                    return new ChromeBrowser();

                case BrowserType.IE:
                    return new InternetExplorerBrowser();

                case BrowserType.Firefox:
                    return new FirefoxBrowser();

                default:
                    throw new ArgumentOutOfRangeException("Unrecognized browser");
            }
        }
Example #29
0
        public static Func<IWebDriver> DriverBuilder(BrowserType browserType)
        {
            switch (browserType)
            {
                case BrowserType.Chrome:
                    return () => new ChromeDriver();

                case BrowserType.IE:
                    return () => new InternetExplorerDriver();

                case BrowserType.Firefox:
                    return () => new FirefoxDriver();

                default:
                    throw new ArgumentOutOfRangeException("Unrecognized browser");
            }
        }
        public static IWebDriver GetBrowser(BrowserType type)
        {
            IWebDriver browser;
            switch (type)
            {
                case BrowserType.Firefox:
                    browser = GetFirefoxBrowser();
                    break;
                case BrowserType.Chrome:
                    browser = GetChromeBrowser();
                    break;
                default:
                    throw new InvalidOperationException("The browser choice is invalid.");
            }

            browser.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(Constants.DefaultImplicitBrowserTimeout));
            return browser;
        }
Example #31
0
 //protected internal ExtentReports Extent;
 //protected internal ExtentTest ETest;
 public BaseTest(BrowserType browserType) : base(browserType)
 {
     // extending the parent class by passing the browser type in parent constructor
 }
Example #32
0
 public Hooks(BrowserType browser)
 {
     _browserType = browser;
 }
        public void ElementDisplayInLaptopModeTest(BrowserType browserType, int width, int height)
        {
            Console.WriteLine($"Browser type - {browserType}, Width - {width}, Height - {height}");
            string deviceType = "Laptop";

            driver     = OpenBrowser(browserType);
            driver.Url = appliFashionV1URL;
            Console.WriteLine(driver.Manage().Window.Size);
            driver.Manage().Window.Size = new System.Drawing.Size(width, height);
            Console.WriteLine(driver.Manage().Window.Size);

            InduceDelay(3);

            //Display of top menu - Home, Men Women etc
            //Display of banner
            //Display of Search text box
            //Display of Filter panel on the left
            //Display of Wishlist image on top right
            //Display of view mode - grid (or) list mode
            //No Display of Filter symbol

            int i = 1;

            Utils.HackathonReport($"---------- Validation for Cross Device Element in LAPTOP mode starts ---------- ", fileName);

            bool topMenuResult = driver.FindElementByXPath(HomePage.topMenuList).Displayed;

            Utils.HackathonReport(i, "Cross Device Element Test - Display of Top Menu", HomePage.topMenuList, browserType.ToString(), width, height, deviceType, (topMenuResult ? "Pass" : "Fail"), fileName);

            bool searchTextBoxResult = driver.FindElementByXPath(HomePage.searchInputField).Displayed;

            Utils.HackathonReport(i++, "Cross Device Element Test - Display of Search text box", HomePage.searchInputField, browserType.ToString(), width, height, deviceType, (searchTextBoxResult ? "Pass" : "Fail"), fileName);

            bool filterPanelResult = driver.FindElementByXPath(HomePage.filterPanel).Displayed;

            Utils.HackathonReport(i++, "Cross Device Element Test - Display of Filter panel on the left", HomePage.filterPanel, browserType.ToString(), width, height, deviceType, (filterPanelResult ? "Pass" : "Fail"), fileName);

            bool wishlistImageResult = driver.FindElementByXPath(HomePage.wishListIcon).Displayed;

            Utils.HackathonReport(i++, "Cross Device Element Test - Display of Wishlist", HomePage.wishListIcon, browserType.ToString(), width, height, deviceType, (wishlistImageResult ? "Pass" : "Fail"), fileName);

            bool viewListResult = driver.FindElementByXPath(HomePage.viewList).Displayed;

            Utils.HackathonReport(i++, "Cross Device Element Test - Display of View Mode - List", HomePage.viewList, browserType.ToString(), width, height, deviceType, (viewListResult ? "Pass" : "Fail"), fileName);

            bool viewGridResult = driver.FindElementByXPath(HomePage.viewGrid).Displayed;

            Utils.HackathonReport(i++, "Cross Device Element Test - Display of View Mode - Grid", HomePage.viewGrid, browserType.ToString(), width, height, deviceType, (viewGridResult ? "Pass" : "Fail"), fileName);

            bool filterSymbolInTableModeResult = !driver.FindElementByXPath(HomePage.filtersAnchorInTabletMode).Displayed;

            Utils.HackathonReport(i++, "Cross Device Element Test - No Display of Filter symbol", HomePage.filtersAnchorInTabletMode, browserType.ToString(), width, height, deviceType, (filterSymbolInTableModeResult ? "Pass" : "Fail"), fileName);

            bool bannerDisplayResult = driver.FindElementByXPath(HomePage.bannerLocator).Displayed;

            Utils.HackathonReport(i++, "Cross Device Element Test - Display of Banner", HomePage.bannerLocator, browserType.ToString(), width, height, deviceType, (bannerDisplayResult ? "Pass" : "Fail"), fileName);

            FooterValidation(browserType, width, height, deviceType, "Cross Device Element Test", i);

            Utils.HackathonReport($"---------- Validation for Cross Device Element in LAPTOP mode ends ---------- ", fileName);

            Assert.IsTrue(topMenuResult &&
                          bannerDisplayResult &&
                          searchTextBoxResult &&
                          filterPanelResult &&
                          wishlistImageResult &&
                          viewListResult &&
                          viewGridResult &&
                          filterSymbolInTableModeResult);
        }
        public void FooterValidation(BrowserType browserType, int width, int height, string deviceType, string testName, int i)
        {
            Console.WriteLine($"Task count for Footer validation for {testName} is {i}");
            Utils.HackathonReport($"---------- Footer Validation for the test - {testName} in {deviceType} starts ---------- ", fileName);

            bool quickLinksHdrResult = driver.FindElementByXPath(HomePage.quickLinksHeader).Displayed;

            Utils.HackathonReport(i, $"{testName} - Footer Validation - Display of Quick Links Header", HomePage.quickLinksHeader, browserType.ToString(), width, height, deviceType, (quickLinksHdrResult ? "Pass" : "Fail"), fileName);

            if (deviceType.Equals("Tablet"))
            {
                driver.FindElementByXPath(HomePage.quickLinksHeader).Click();
            }
            bool aboutUsResult = driver.FindElementByXPath(HomePage.aboutUs).Displayed;

            Utils.HackathonReport(i++, $"{testName} - Footer Validation - Display of About Us", HomePage.aboutUs, browserType.ToString(), width, height, deviceType, (aboutUsResult ? "Pass" : "Fail"), fileName);

            bool faqResult = driver.FindElementByXPath(HomePage.faq).Displayed;

            Utils.HackathonReport(i++, $"{testName} - Footer Validation - Display of FAQ", HomePage.faq, browserType.ToString(), width, height, deviceType, (faqResult ? "Pass" : "Fail"), fileName);

            bool helpResult = driver.FindElementByXPath(HomePage.help).Displayed;

            Utils.HackathonReport(i++, $"{testName} - Footer Validation - Display of Help", HomePage.help, browserType.ToString(), width, height, deviceType, (helpResult ? "Pass" : "Fail"), fileName);

            bool myAccountResult = driver.FindElementByXPath(HomePage.myAccount).Displayed;

            Utils.HackathonReport(i++, $"{testName} - Footer Validation - Display of My Account", HomePage.myAccount, browserType.ToString(), width, height, deviceType, (myAccountResult ? "Pass" : "Fail"), fileName);

            bool blogResult = driver.FindElementByXPath(HomePage.blog).Displayed;

            Utils.HackathonReport(i++, $"{testName} - Footer Validation - Display of Blog", HomePage.blog, browserType.ToString(), width, height, deviceType, (blogResult ? "Pass" : "Fail"), fileName);

            bool contactsResult = driver.FindElementByXPath(HomePage.contacts).Displayed;

            Utils.HackathonReport(i++, $"{testName} - Footer Validation - Display of Contacts under Quick Links", HomePage.contacts, browserType.ToString(), width, height, deviceType, (contactsResult ? "Pass" : "Fail"), fileName);

            if (deviceType.Equals("Tablet"))
            {
                driver.FindElementByXPath(HomePage.quickLinksHeader).Click();
            }

            InduceDelay(2);

            if (deviceType.Equals("Tablet"))
            {
                driver.FindElementByXPath(HomePage.contactsHeader).Click();
            }

            bool contactHomeAddrResult = driver.FindElementByXPath(HomePage.contactsHomeAddress).Displayed;

            Utils.HackathonReport(i++, $"{testName} - Footer Validation - Display of Contacts - Home Address", HomePage.contactsHomeAddress, browserType.ToString(), width, height, deviceType, (contactHomeAddrResult ? "Pass" : "Fail"), fileName);

            bool contactEmailAddrResult = driver.FindElementByXPath(HomePage.contactsEmailAddress).Displayed;

            Utils.HackathonReport(i++, $"{testName} - Footer Validation - Display of Contacts - Email Address", HomePage.contactsEmailAddress, browserType.ToString(), width, height, deviceType, (contactEmailAddrResult ? "Pass" : "Fail"), fileName);

            if (deviceType.Equals("Tablet"))
            {
                driver.FindElementByXPath(HomePage.contactsHeader).Click();
            }

            InduceDelay(2);

            if (deviceType.Equals("Tablet"))
            {
                driver.FindElementByXPath(HomePage.keepInTouchHeader).Click();
            }

            bool keepInTouchHdrResult = driver.FindElementByXPath(HomePage.keepInTouchHeader).Displayed;

            Utils.HackathonReport(i++, $"{testName} - Footer Validation - Display of Keep In Touch Header", HomePage.keepInTouchHeader, browserType.ToString(), width, height, deviceType, (keepInTouchHdrResult ? "Pass" : "Fail"), fileName);

            bool keepInTouchTxtBoxResult = driver.FindElementByXPath(HomePage.keepInTouchTextBox).Displayed;

            Utils.HackathonReport(i++, $"{testName} - Footer Validation - Display of Keep In Touch Textbox", HomePage.keepInTouchTextBox, browserType.ToString(), width, height, deviceType, (keepInTouchTxtBoxResult ? "Pass" : "Fail"), fileName);

            bool keepInTouchSubmitBtnResult = driver.FindElementByXPath(HomePage.keepInTouchSubmitBtn).Displayed;

            Utils.HackathonReport(i++, $"{testName} - Footer Validation - Display of Keep In Touch Submit button", HomePage.keepInTouchSubmitBtn, browserType.ToString(), width, height, deviceType, (keepInTouchSubmitBtnResult ? "Pass" : "Fail"), fileName);

            if (deviceType.Equals("Tablet"))
            {
                driver.FindElementByXPath(HomePage.keepInTouchHeader).Click();
            }

            bool langSelectorResult = driver.FindElementByXPath(HomePage.languageLocator).Displayed;

            Utils.HackathonReport(i++, $"{testName} - Footer Validation - Display of Language Selector", HomePage.languageLocator, browserType.ToString(), width, height, deviceType, (langSelectorResult ? "Pass" : "Fail"), fileName);

            bool currencySelectorResult = driver.FindElementByXPath(HomePage.currencySelectorLocator).Displayed;

            Utils.HackathonReport(i++, $"{testName} - Footer Validation - Display of Currency Selector", HomePage.currencySelectorLocator, browserType.ToString(), width, height, deviceType, (currencySelectorResult ? "Pass" : "Fail"), fileName);

            bool termsAndCondnResult = driver.FindElementByXPath(HomePage.termsAndConditionLocator).Displayed;

            Utils.HackathonReport(i++, $"{testName} - Footer Validation - Display of Terms and Conditions", HomePage.termsAndConditionLocator, browserType.ToString(), width, height, deviceType, (termsAndCondnResult ? "Pass" : "Fail"), fileName);

            bool privacyResult = driver.FindElementByXPath(HomePage.privacyLocator).Displayed;

            Utils.HackathonReport(i++, $"{testName} - Footer Validation - Display of Privacy", HomePage.privacyLocator, browserType.ToString(), width, height, deviceType, (privacyResult ? "Pass" : "Fail"), fileName);

            bool trademarkResult = driver.FindElementByXPath(HomePage.trademarkLocator).Displayed;

            Utils.HackathonReport(i++, $"{testName} - Footer Validation - Display of Trademark", HomePage.trademarkLocator, browserType.ToString(), width, height, deviceType, (trademarkResult ? "Pass" : "Fail"), fileName);
        }
 public BrowserType PassInBrowser(string Browsertype)
 {
     return(_browserType = (BrowserType)Enum.Parse(typeof(BrowserType), Browsertype));
 }
Example #36
0
 public BaseTest(BrowserType browserType) : base(browserType)
 {
 }
Example #37
0
        /// <summary>
        /// Creates the web driver.
        /// </summary>
        /// <param name="browserType">Type of the browser.</param>
        /// <param name="browserFactoryConfiguration">The browser factory configuration.</param>
        /// <returns>The created web driver.</returns>
        /// <exception cref="System.InvalidOperationException">Thrown if the browser is not supported.</exception>
        internal static IWebDriver CreateWebDriver(BrowserType browserType, BrowserFactoryConfigurationElement browserFactoryConfiguration)
        {
            IWebDriver driver;

            if (!RemoteDriverExists(browserFactoryConfiguration.Settings, browserType, out driver))
            {
                switch (browserType)
                {
                case BrowserType.IE:
                    var explorerOptions = new InternetExplorerOptions {
                        EnsureCleanSession = browserFactoryConfiguration.EnsureCleanSession
                    };
                    var internetExplorerDriverService = InternetExplorerDriverService.CreateDefaultService();
                    internetExplorerDriverService.HideCommandPromptWindow = true;
                    driver = new InternetExplorerDriver(internetExplorerDriverService, explorerOptions);
                    break;

                case BrowserType.FireFox:
                    driver = GetFireFoxDriver(browserFactoryConfiguration);
                    break;

                case BrowserType.Chrome:
                    var chromeOptions = new ChromeOptions {
                        LeaveBrowserRunning = false
                    };
                    var chromeDriverService = ChromeDriverService.CreateDefaultService();
                    chromeDriverService.HideCommandPromptWindow = true;

                    driver = new ChromeDriver(chromeDriverService, chromeOptions);
                    break;

                case BrowserType.PhantomJS:
                    var phantomJsDriverService = PhantomJSDriverService.CreateDefaultService();
                    phantomJsDriverService.HideCommandPromptWindow = true;
                    driver = new PhantomJSDriver(phantomJsDriverService);
                    break;

                case BrowserType.Safari:
                    driver = new SafariDriver();
                    break;

                default:
                    throw new InvalidOperationException(string.Format("Browser type '{0}' is not supported in Selenium local mode. Did you mean to configure a remote driver?", browserType));
                }
            }

            // Set Driver Settings
            var managementSettings = driver.Manage();

            // Set timeouts

            var applicationConfiguration = SpecBind.Helpers.SettingHelper.GetConfigurationSection().Application;

            managementSettings.Timeouts()
            .ImplicitlyWait(browserFactoryConfiguration.ElementLocateTimeout)
            .SetPageLoadTimeout(browserFactoryConfiguration.PageLoadTimeout);

            ActionBase.DefaultTimeout              = browserFactoryConfiguration.ElementLocateTimeout;
            WaitForPageAction.DefaultTimeout       = browserFactoryConfiguration.PageLoadTimeout;
            ActionBase.RetryValidationUntilTimeout = applicationConfiguration.RetryValidationUntilTimeout;

            // Maximize window
            managementSettings.Window.Maximize();

            return(driver);
        }
Example #38
0
        /// <summary>
        /// Checks to see if settings for the remote driver exists.
        /// </summary>
        /// <param name="settings">The settings.</param>
        /// <param name="browserType">Type of the browser.</param>
        /// <param name="remoteWebDriver">The created remote web driver.</param>
        /// <returns><c>true</c> if the settings exist; otherwise <c>false</c>.</returns>
        private static bool RemoteDriverExists(NameValueConfigurationCollection settings, BrowserType browserType, out IWebDriver remoteWebDriver)
        {
            var remoteUri = GetRemoteDriverUri(settings);

            if (remoteUri == null)
            {
                remoteWebDriver = null;
                return(false);
            }

            DesiredCapabilities capability;

            switch (browserType)
            {
            case BrowserType.IE:
                capability = DesiredCapabilities.InternetExplorer();
                break;

            case BrowserType.FireFox:
                capability = DesiredCapabilities.Firefox();
                break;

            case BrowserType.Chrome:
                capability = DesiredCapabilities.Chrome();
                break;

            case BrowserType.Safari:
                capability = DesiredCapabilities.Safari();
                break;

            case BrowserType.Opera:
                capability = DesiredCapabilities.Opera();
                break;

            case BrowserType.Android:
                capability = DesiredCapabilities.Android();
                break;

            case BrowserType.iPhone:
                capability = DesiredCapabilities.IPhone();
                break;

            case BrowserType.iPad:
                capability = DesiredCapabilities.IPad();
                break;

            case BrowserType.PhantomJS:
                capability = DesiredCapabilities.PhantomJS();
                break;

            case BrowserType.Edge:
                capability = DesiredCapabilities.Edge();
                break;

            default:
                throw new InvalidOperationException(string.Format("Browser Type '{0}' is not supported as a remote driver.", browserType));
            }

            // Add any additional settings that are not reserved
            var reservedSettings = new[] { RemoteUrlSetting };

            foreach (var setting in settings.OfType <NameValueConfigurationElement>()
                     .Where(s => reservedSettings.All(r => !string.Equals(r, s.Name, StringComparison.OrdinalIgnoreCase))))
            {
                capability.SetCapability(setting.Name, setting.Value);
            }

            remoteWebDriver = new RemoteScreenshotWebDriver(remoteUri, capability);
            return(true);
        }
Example #39
0
        private void PerformContactUsTest(BrowserType browserType)
        {
            // Initialize web driver
            IWebDriver webDriver = DriverUtilities.CreateDriver(browserType);

            Assert.IsNotNull(webDriver, "Could not acquire driver for :" + browserType);

            webDriver.Navigate().GoToUrl(LocatorHelper.HOME_PAGE_URL);

            // Accept all cookies
            IWebElement acceptAllCookiesButton = LocatorHelper.FindServicePageControl(webDriver, ServicePageLocatorName.AcceptAllCookies);

            acceptAllCookiesButton.Click();

            // Navigate to services and automation page
            IWebElement serviceMainMenu = LocatorHelper.FindServicePageControl(webDriver, ServicePageLocatorName.ServiceMainMenu);

            serviceMainMenu.Click();

            IWebElement automationLink = LocatorHelper.FindServicePageControl(webDriver, ServicePageLocatorName.AutomationSubMenu);

            automationLink.Click();

            // Suffix to generate random texts
            string suffix = DateTime.Now.ToString("_yyyy_MM_dd_HH_mm_ss");

            // Generate random texts for required fields
            IWebElement firstName = LocatorHelper.FindContactUsControl(webDriver, ContactUsLocatorName.FirstName);

            firstName.SendKeys("FirstName" + suffix);

            IWebElement lastName = LocatorHelper.FindContactUsControl(webDriver, ContactUsLocatorName.LastName);

            lastName.SendKeys("LastName" + suffix);

            IWebElement email = LocatorHelper.FindContactUsControl(webDriver, ContactUsLocatorName.EMail);

            email.SendKeys(suffix + "@a.com");

            IWebElement phone = LocatorHelper.FindContactUsControl(webDriver, ContactUsLocatorName.Phone);

            phone.SendKeys("0049");

            IWebElement country = LocatorHelper.FindContactUsControl(webDriver, ContactUsLocatorName.Country);

            country.SendKeys("Germany");

            IWebElement message = LocatorHelper.FindContactUsControl(webDriver, ContactUsLocatorName.Message);

            message.SendKeys("some message" + suffix);

            // Click on Agree checkbox
            IWebElement agreement = LocatorHelper.FindContactUsControl(webDriver, ContactUsLocatorName.Agreement);

            agreement.Click();


            // Note : Captcha stops the test run here.
            // Captcha has been introduced to stop the automated usage of website hence this does not let us to continue further.
            // Please see the following pseudo code.

            //IWebElement captcha = LocatorHelper.FindContactUsControl(webDriver, ContactUsLocatorName.Captcha);

            //IWebElement submit = LocatorHelper.FindContactUsControl(webDriver, ContactUsLocatorName.Submit);
            //submit.Click();

            //IWebElement thankYouDiv = LocatorHelper.FindContactUsControl(webDriver, ContactUsLocatorName.ThankYou);
            //if (thankYouDiv == null || !thankYouDiv.Text.Contains("Thank you for contacting us."))
            //    Assert.Fail("Expected 'Thank you message' missing on Contact Us submit action");


            // Exit the driver
            DriverUtilities.DisposeDriver(webDriver);
        }
Example #40
0
 public XrmBrowser(BrowserType type) : base(type)
 {
 }
Example #41
0
 public HorizontalSliderPage(BrowserType browser) : base(browser)
 {
     this.sliderLocator       = "input[type=\"range\"]";
     this.sliderResultLocator = "range";
 }
 public IWebDriver Create(BrowserType browserType, string logPath)
 {
     return webDriverFactories.Single(f => f.CanCreate(browserType)).Create(logPath);
 }
Example #43
0
        public async Task Shows_Error_When_Joining_Not_Existing_Team(bool serverSide, BrowserType browserType)
        {
            Contexts.Add(new BrowserTestContext(
                             nameof(ScrumMasterTest),
                             nameof(Shows_Error_When_Joining_Not_Existing_Team),
                             browserType,
                             serverSide));

            await StartServer();

            StartClients();

            string team   = "My team";
            string member = "Test Member";

            await ClientTest.OpenApplication();

            TakeScreenshot("01-Loading");
            ClientTest.AssertIndexPage();
            TakeScreenshot("02-Index");
            ClientTest.FillJoinTeamForm(team, member);
            TakeScreenshot("03-JoinTeamForm");
            ClientTest.SubmitJoinTeamForm();
            await Task.Delay(500);

            ClientTest.AssertIndexPage();
            TakeScreenshot("04-Error");
            ClientTest.AssertMessageBox("Scrum Team \"My team\" does not exist. (Parameter 'teamName')");
        }
Example #44
0
 public Browser(BrowserType browserType)
 => Type = browserType;
 /// <summary>
 /// Initializes a new instance of the <see cref="LoginTest"/> class.
 /// </summary>
 /// <param name="browser">
 /// The browser type which we would like to run our tests on.
 /// </param>
 public LoginTest(BrowserType browser)
 {
     this.currentType = browser;
 }
Example #46
0
 public Base(BrowserType browser)
 {
     _BrowserType = browser;
 }
Example #47
0
 public Hooks(BrowserType browser)
 {
     _browserType = browser;
     //Driver = new FirefoxDriver(@"C:\Users\jcmon\source\repos\SeleniumParallelTest\SeleniumParallelTest\bin\Debug"); //windows
     //Driver = new FirefoxDriver("/Users/JuanCMontoya/Projects/test/SeleniumParallelTest/bin/Debug"); // mac
 }
Example #48
0
 protected BaseTest(BrowserType browserType)
 {
     _driverFactory     = new WebDriverFactory();
     _actualBrowserType = browserType;
 }
 public Hooks(BrowserType browserType)
 {
     _browserType = browserType;
 }
Example #50
0
        public void InitWebDriver(BrowserType browsertype)

        {
            ObjectRepository.Config = new AppConfigReader();



            if (browsertype == BrowserType.Chrome)
            {
                O.Driver = GetChromeDriver();
            }


            else if (browsertype == BrowserType.IExplorer)
            {
                O.Driver = GetIEDriver();
            }


            else if (browsertype == BrowserType.Firefox)
            {
                O.Driver = GetFirefoxDriver();
            }



            //switch (ObjectRepository.Config.GetBrowser())
            //{
            //    case BrowserType.Firefox:
            //        ObjectRepository.Driver = GetFirefoxDriver();
            //        //  Logger.Info(" Using Firefox Driver  ");



            //        break;

            //    case BrowserType.Chrome:
            //        ObjectRepository.Driver = GetChromeDriver();
            //        //      Logger.Info(" Using Chrome Driver  ");


            //       break;

            //    case BrowserType.IExplorer:
            //        ObjectRepository.Driver = GetIEDriver();
            //        //    Logger.Info(" Using Internet Explorer Driver  ");


            //        break;



            //    default:
            //        throw new NoSuitableDriverFound("Driver Not Found : " + ObjectRepository.Config.GetBrowser().ToString());



            O.Driver.Manage()
            .Timeouts().PageLoad = TimeSpan.FromSeconds(ObjectRepository.Config.GetPageLoadTimeOut());



            O.Driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(ObjectRepository.Config.GetElementLoadTimeOut());


            O.Driver.Manage().Window.Maximize();
            //BrowserHelper.BrowserMaximize();



            //*************************************relevantcodes...extenttest 2.41.0************************

            // creating tests

            //  ExtentTest tests = extent.createTest(method.getName());
            // parentTest.set(tests);

            //ExtentTest testclass = parentTest.get().createNode(getClass().getSimpleName());

            //childTest.set(testclass);


            //ExtentTest testmethod = childTest.get().createNode(method.getName());

            //childTestnew.set(testmethod);



            //**********************************************************************



            //*************************************aventstack...extenttest 3.0.0************************



            // creating nodes	            //  parentTest = extent.CreateTest("MyFirstTest");

            parentTest = extent.CreateTest(TestContext.CurrentContext.Test.ClassName);

            childTest = parentTest.CreateNode(TestContext.CurrentContext.Test.MethodName);


            childTestnew = childTest.CreateNode(TestContext.CurrentContext.Test.Name);
        }
        public void ValidateProductDetailsPage(BrowserType browserType, int width, int height, string deviceType)
        {
            //Validate the below points
            //Display of Product Name
            //Display of Product Image
            //Display of Product Rating
            //Display of Product Description
            //Display of Size label and Size dropdown
            //Display of Quantity label, Quantity text box
            //Display of Quantity increment and decrement buttons
            //Display of new price, old price and discount percentage
            //Display of Add to cart button

            int i = 1;

            bool nameResult = driver.FindElementByXPath(PDPage.h1Locator).Displayed;

            Utils.HackathonReport(i, "Product Details Test - Display of Product Name", PDPage.h1Locator, browserType.ToString(), width, height, deviceType, (nameResult ? "Pass" : "Fail"), fileName);

            bool imageResult = driver.FindElementByXPath(PDPage.shoeImageLocator).Displayed;

            Utils.HackathonReport(i++, "Product Details Test - Display of Product Image", PDPage.shoeImageLocator, browserType.ToString(), width, height, deviceType, (imageResult ? "Pass" : "Fail"), fileName);

            bool ratingResult = driver.FindElementByXPath(PDPage.ratingLocator).Displayed;

            Utils.HackathonReport(i++, "Product Details Test - Display of Product Rating", PDPage.ratingLocator, browserType.ToString(), width, height, deviceType, (ratingResult ? "Pass" : "Fail"), fileName);

            bool descriptionResult = driver.FindElementByXPath(PDPage.productDescriptionLocator).Displayed;

            Utils.HackathonReport(i++, "Product Details Test - Display of Product Description", PDPage.productDescriptionLocator, browserType.ToString(), width, height, deviceType, (descriptionResult ? "Pass" : "Fail"), fileName);

            bool sizeLabelResult = driver.FindElementByXPath(PDPage.sizeLabelLocator).Displayed;

            Utils.HackathonReport(i++, "Product Details Test - Display of Size label", PDPage.sizeLabelLocator, browserType.ToString(), width, height, deviceType, (sizeLabelResult ? "Pass" : "Fail"), fileName);

            //Click on the dropdown
            driver.FindElementByXPath(PDPage.sizeDropdownLocator).Click();
            bool sizeDropdownResult = driver.FindElementByXPath(PDPage.sizeDropdownListLocator).Displayed;

            driver.FindElementByXPath(PDPage.sizeDropdownLocator).Click();
            Utils.HackathonReport(i++, "Product Details Test - Display of Size Dropdown", PDPage.sizeDropdownListLocator, browserType.ToString(), width, height, deviceType, (sizeDropdownResult ? "Pass" : "Fail"), fileName);

            bool qtyLabelResult = driver.FindElementByXPath(PDPage.quantityLabelLocator).Displayed;

            Utils.HackathonReport(i++, "Product Details Test - Display of Quantity Label", PDPage.quantityLabelLocator, browserType.ToString(), width, height, deviceType, (qtyLabelResult ? "Pass" : "Fail"), fileName);

            bool qtyIncBtnResult = driver.FindElementByXPath(PDPage.quantityIncBtnLocator).Displayed;

            Utils.HackathonReport(i++, "Product Details Test - Display of Quantity Increment Button", PDPage.quantityLabelLocator, browserType.ToString(), width, height, deviceType, (qtyIncBtnResult ? "Pass" : "Fail"), fileName);

            bool qtyDecBtnResult = driver.FindElementByXPath(PDPage.quantityDecBtnLocator).Displayed;

            Utils.HackathonReport(i++, "Product Details Test - Display of Quantity Decrement Button", PDPage.quantityDecBtnLocator, browserType.ToString(), width, height, deviceType, (qtyDecBtnResult ? "Pass" : "Fail"), fileName);

            bool addToCartBtnResult = driver.FindElementByXPath(PDPage.addToCartAnchorLocator).Displayed;

            Utils.HackathonReport(i++, "Product Details Test - Display of Add To Cart Button", PDPage.addToCartAnchorLocator, browserType.ToString(), width, height, deviceType, (addToCartBtnResult ? "Pass" : "Fail"), fileName);

            bool newPriceResult = driver.FindElementByXPath(PDPage.newPriceLocator).Displayed;

            Utils.HackathonReport(i++, "Product Details Test - Display of New Price", PDPage.newPriceLocator, browserType.ToString(), width, height, deviceType, (newPriceResult ? "Pass" : "Fail"), fileName);

            bool oldPriceResult = driver.FindElementByXPath(PDPage.oldPriceLocator).Displayed;

            Utils.HackathonReport(i++, "Product Details Test - Display of Old Price", PDPage.newPriceLocator, browserType.ToString(), width, height, deviceType, (oldPriceResult ? "Pass" : "Fail"), fileName);

            bool discountResult = driver.FindElementByXPath(PDPage.discountLocator).Displayed;

            Utils.HackathonReport(i++, "Product Details Test - Display of Discount", PDPage.newPriceLocator, browserType.ToString(), width, height, deviceType, (discountResult ? "Pass" : "Fail"), fileName);

            FooterValidation(browserType, width, height, deviceType, "Product Details Test", i);
        }
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public async Task <DisconnectReason> ReceiveAsync(string vid, BrowserType browserType)
        {
            _disconnectReason = DisconnectReason.Unknown;
            string liveChatHtml = await GetLiveChatHtml(vid);

            string ytInitialData;

            try
            {
                ytInitialData = Tools.ExtractYtInitialDataFromLiveChatHtml(liveChatHtml);
            }
            catch (ParseException ex)
            {
                _logger.LogException(ex, "live_chatからのytInitialDataの抜き出しに失敗", liveChatHtml);
                return(DisconnectReason.YtInitialDataNotFound);
            }
            IContinuation      initialContinuation;
            ChatContinuation   chatContinuation;
            List <CommentData> initialCommentData;

            try
            {
                (initialContinuation, chatContinuation, initialCommentData) = Tools.ParseYtInitialData(ytInitialData);
            }
            catch (YouTubeLiveServerErrorException ex)
            {
                _logger.LogException(ex, "サーバエラー", $"ytInitialData={ytInitialData},vid={vid}");
                return(DisconnectReason.ServerError);
            }
            catch (ContinuationNotExistsException)
            {
                //放送終了
                return(DisconnectReason.Finished);
            }
            catch (ChatUnavailableException)
            {
                //SendInfo("この配信ではチャットが無効になっているようです", InfoType.Error);
                return(DisconnectReason.ChatUnavailable);
            }
            catch (Exception ex)
            {
                _logger.LogException(ex, "未知の例外", $"ytInitialData={ytInitialData},vid={vid}");
                return(DisconnectReason.Unknown);
            }

            Connected?.Invoke(this, EventArgs.Empty);

            //直近の過去コメントを送る。
            foreach (var data in initialCommentData)
            {
                if (_receivedCommentIds.Contains(data.Id))
                {
                    continue;
                }
                else
                {
                    _receivedCommentIds.Add(data.Id);
                }
                var messageContext = CreateMessageContext(data, true);
                MessageReceived?.Invoke(this, messageContext);
            }
            //コメント投稿に必要なものの準備
            PrepareForPostingComments(liveChatHtml, ytInitialData);

            var  tasks             = new List <Task>();
            Task activeCounterTask = null;
            IActiveCounter <string> activeCounter = null;

            if (_options.IsActiveCountEnabled)
            {
                activeCounter = new ActiveCounter <string>()
                {
                    CountIntervalSec = _options.ActiveCountIntervalSec,
                    MeasureSpanMin   = _options.ActiveMeasureSpanMin,
                };
                activeCounter.Updated += (s, e) =>
                {
                    MetadataUpdated?.Invoke(this, new Metadata {
                        Active = e.ToString()
                    });
                };
                activeCounterTask = activeCounter.Start();
                tasks.Add(activeCounterTask);
            }

            IMetadataProvider metaProvider = null;
            var metaTask = CreateMetadataReceivingTask(ref metaProvider, browserType, vid, liveChatHtml);

            if (metaTask != null)
            {
                tasks.Add(metaTask);
            }

            _chatProvider = new ChatProvider(_server, _logger);
            _chatProvider.ActionsReceived += (s, e) =>
            {
                foreach (var action in e)
                {
                    if (_receivedCommentIds.Contains(action.Id))
                    {
                        continue;
                    }
                    else
                    {
                        activeCounter?.Add(action.Id);
                        _receivedCommentIds.Add(action.Id);
                    }

                    var messageContext = CreateMessageContext(action, false);
                    MessageReceived?.Invoke(this, messageContext);
                }
            };
            _chatProvider.InfoReceived += (s, e) =>
            {
                SendInfo(e.Comment, e.Type);
            };
            var continuation = _siteOptions.IsAllChat ? chatContinuation.AllChatContinuation : chatContinuation.JouiChatContinuation;
            var chatTask     = _chatProvider.ReceiveAsync(continuation);

            tasks.Add(chatTask);

            _disconnectReason = DisconnectReason.Finished;
            while (tasks.Count > 0)
            {
                var t = await Task.WhenAny(tasks);

                if (t == metaTask)
                {
                    try
                    {
                        await metaTask;
                    }
                    catch (Exception ex)
                    {
                        _logger.LogException(ex, "metaTaskが終了した原因");
                    }
                    //metaTask内でParseExceptionもしくはDisconnect()
                    //metaTaskは終わっても良い。
                    tasks.Remove(metaTask);
                    metaProvider = null;
                }
                else if (t == activeCounterTask)
                {
                    try
                    {
                        await activeCounterTask;
                    }
                    catch (Exception ex)
                    {
                        _logger.LogException(ex, "activeCounterTaskが終了した原因");
                    }
                    tasks.Remove(activeCounterTask);
                    activeCounter = null;
                }
                else //chatTask
                {
                    tasks.Remove(chatTask);
                    try
                    {
                        await chatTask;
                    }
                    catch (ReloadException ex)
                    {
                        _logger.LogException(ex, "", $"vid={vid}");
                        _disconnectReason = DisconnectReason.Reload;
                    }
                    catch (Exception ex)
                    {
                        _logger.LogException(ex);
                        _disconnectReason = DisconnectReason.Unknown;
                    }
                    _chatProvider = null;

                    //chatTaskが終わったらmetaTaskも終了させる
                    metaProvider?.Disconnect();
                    if (metaTask != null)
                    {
                        try
                        {
                            await metaTask;
                        }
                        catch (Exception ex)
                        {
                            _logger.LogException(ex, "metaTaskが終了した原因");
                        }
                        tasks.Remove(metaTask);
                    }
                    metaProvider = null;

                    activeCounter?.Stop();
                    if (activeCounterTask != null)
                    {
                        try
                        {
                            await activeCounterTask;
                        }
                        catch (Exception ex)
                        {
                            _logger.LogException(ex, "activeCounterTaskが終了した原因");
                        }
                        tasks.Remove(activeCounterTask);
                    }
                    activeCounter = null;
                }
            }
            return(_disconnectReason);
        }
Example #53
0
 public GoogleTesting(BrowserType browser) : base(browser)
 {
 }
 public BrowserAttribute(BrowserType browserType)
 {
     _driver = DriverFactory.Create(browserType);
 }
Example #55
0
        public async Task ShouldRejectIfExecutablePathIsInvalid()
        {
            var options = TestConstants.GetDefaultBrowserOptions();

            options.ExecutablePath = "random-invalid-path";

            var exception = await Assert.ThrowsAsync <PlaywrightSharpException>(() => BrowserType.LaunchAsync(options));

            Assert.Contains("Failed to launch", exception.Message);
            Assert.Contains("pass `debug: \"pw:api\"` to LaunchAsync", exception.Message);
        }
Example #56
0
        internal static void CheckExpectations(ExceptionTracker exceptionTracker, SignalX signalX, int numberOfClients, Action operation, string url, List <TestObject> testObjects, BrowserType browserType = BrowserType.Default, TestEventHandler events = null)
        {
            Thread thread         = null;
            var    browserProcess = new List <Process>();

            /*
             *
             */
            //https://stackoverflow.com/questions/22538457/put-a-string-with-html-javascript-into-selenium-webdriver
            //https://www.automatetheplanet.com/selenium-webdriver-csharp-cheat-sheet/
            var option = new FirefoxOptions();

            option.AddArgument("--headless");
            var _drivers = new List <IWebDriver>();

            if (browserType == BrowserType.HeadlessBrowser)
            {
                for (int i = 0; i < testObjects.Count; i++)
                {
                    _drivers.Add(
                        new FirefoxDriver(
                            option
                            // Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                            ));
                }
            }

            try
            {
                using (WebApp.Start <Startup>(url))
                {
                    events?.OnAppStarted?.Invoke();

                    thread = new Thread(
                        () =>
                    {
                        try
                        {
                            for (int i = 0; i < testObjects.Count; i++)
                            {
                                TestObject testObject = testObjects[i];
                                if (browserType == BrowserType.SystemBrowser)
                                {
                                    browserProcess.Add(Process.Start(url + testObject.FileName));
                                }

                                if (browserType == BrowserType.Default || browserType == BrowserType.HeadlessBrowser)
                                {
                                    _drivers[i].Navigate().GoToUrl(url);
                                    ((IJavaScriptExecutor)_drivers[i]).ExecuteScript($"arguments[0].innerHTML = '{testObject.PageHtml}'");
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            events?.OnClientError?.Invoke(new AggregateException(e, exceptionTracker.Exception));
                        }
                    });
                    thread.SetApartmentState(ApartmentState.STA);
                    thread.Start();

                    // SpinWait.SpinUntil(() => (!SignalX.Settings.HasOneOrMoreConnections || SignalX.CurrentNumberOfConnections < (ulong)numberOfClients), MaxTestWaitTimeBeforeChecks);

                    AwaitAssert(
                        () =>
                    {
                        if (!signalX.Settings.HasOneOrMoreConnections)
                        {
                            throw new Exception("No connection received from any client.This may also be caused by a slow connection " + exceptionTracker?.Exception?.Message);
                        }

                        if (signalX.ConnectionCount < (ulong)numberOfClients)
                        {
                            throw new Exception($"Wait timeout for expected number of clients {numberOfClients} to show up.This may also be caused by a slow connection " + exceptionTracker?.Exception?.Message);
                        }
                    },
                        () =>
                    {
                        if (exceptionTracker.Exception != null)
                        {
                            throw exceptionTracker.Exception;
                        }
                    },
                        MaxWaitTimeForAllExpectedConnectionsToArrive);

                    new SignalXAssertionLib().WaitForSomeTime(MaxTestWaitTimeBeforeChecks);

                    events?.OnClientLoaded?.Invoke();
                    //wait for some time before checks to allow side effects to occur
                    AwaitAssert(
                        () =>
                    {
                        operation();
                        //if we got this far, then we made it
                        events?.OnCheckSucceeded?.Invoke();
                    },
                        () =>
                    {
                        if (exceptionTracker.Exception != null)
                        {
                            throw exceptionTracker.Exception;
                        }
                    },
                        MaxTestTimeSpan,
                        null,
                        ex =>
                    {
                        //to handle both exceptions
                        if (exceptionTracker.Exception != null)
                        {
                            events?.OnFinally?.Invoke(exceptionTracker.Exception);
                        }
                        else
                        {
                            events?.OnFinally?.Invoke(ex);
                        }
                    },
                        events?.OnCheckFailures);
                }
            }
            finally
            {
                QuitAllBrowsers(_drivers, browserProcess, thread, testObjects, browserType);
                signalX.Dispose();
            }
        }
 public BrowserAttribute(BrowserType browser, MobileWindowSize mobileWindowSize, Lifecycle behavior = Lifecycle.NotSet, bool shouldAutomaticallyScrollToVisible = true, bool shouldCaptureHttpTraffic = false)
     : this(browser, behavior, shouldCaptureHttpTraffic)
     => Size = WindowsSizeResolver.GetWindowSize(mobileWindowSize);
Example #58
0
        private BrowserConfiguration GetCurrentBrowserConfiguration(Bellatrix.Plugins.PluginEventArgs e)
        {
            var    browserAttribute = GetBrowserAttribute(e.TestMethodMemberInfo, e.TestClassType);
            string fullClassName    = e.TestClassType.FullName;

            if (browserAttribute != null)
            {
                BrowserType currentBrowserType = browserAttribute.Browser;

                Lifecycle     currentLifecycle                   = browserAttribute.Lifecycle;
                bool          shouldCaptureHttpTraffic           = browserAttribute.ShouldCaptureHttpTraffic;
                bool          shouldAutomaticallyScrollToVisible = browserAttribute.ShouldAutomaticallyScrollToVisible;
                Size          currentBrowserSize                 = browserAttribute.Size;
                ExecutionType executionType = browserAttribute.ExecutionType;

                var options = (browserAttribute as IDriverOptionsAttribute)?.CreateOptions(e.TestMethodMemberInfo, e.TestClassType) ?? GetDriverOptionsBasedOnBrowser(currentBrowserType, e.TestClassType);
                InitializeCustomCodeOptions(options, e.TestClassType);

                var browserConfiguration = new BrowserConfiguration(executionType, currentLifecycle, currentBrowserType, currentBrowserSize, fullClassName, shouldCaptureHttpTraffic, shouldAutomaticallyScrollToVisible, options);
                e.Container.RegisterInstance(browserConfiguration, "_currentBrowserConfiguration");

                return(browserConfiguration);
            }
            else
            {
                BrowserType currentBrowserType = Parse <BrowserType>(ConfigurationService.GetSection <WebSettings>().ExecutionSettings.DefaultBrowser);

                if (e.Arguments != null & e.Arguments.Any())
                {
                    if (e.Arguments[0] is BrowserType)
                    {
                        currentBrowserType = (BrowserType)e.Arguments[0];
                    }
                }

                Lifecycle currentLifecycle = Parse <Lifecycle>(ConfigurationService.GetSection <WebSettings>().ExecutionSettings.DefaultLifeCycle);

                Size currentBrowserSize = default;
                if (!string.IsNullOrEmpty(ConfigurationService.GetSection <WebSettings>().ExecutionSettings.Resolution))
                {
                    currentBrowserSize = WindowsSizeResolver.GetWindowSize(ConfigurationService.GetSection <WebSettings>().ExecutionSettings.Resolution);
                }

                ExecutionType executionType                      = ConfigurationService.GetSection <WebSettings>().ExecutionSettings.ExecutionType.ToLower() == "regular" ? ExecutionType.Regular : ExecutionType.Grid;
                bool          shouldCaptureHttpTraffic           = ConfigurationService.GetSection <WebSettings>().ShouldCaptureHttpTraffic;
                bool          shouldAutomaticallyScrollToVisible = ConfigurationService.GetSection <WebSettings>().ShouldAutomaticallyScrollToVisible;
                var           options = GetDriverOptionsBasedOnBrowser(currentBrowserType, e.TestClassType);

                if (!string.IsNullOrEmpty(ConfigurationService.GetSection <WebSettings>().ExecutionSettings.BrowserVersion))
                {
                    options.BrowserVersion = ConfigurationService.GetSection <WebSettings>().ExecutionSettings.BrowserVersion;
                }

                if (e.Arguments != null & e.Arguments.Count >= 2)
                {
                    if (e.Arguments[0] is BrowserType && e.Arguments[1] is int)
                    {
                        options.BrowserVersion = e.Arguments[1].ToString();
                    }
                }

                string testName = e.TestFullName != null?e.TestFullName.Replace(" ", string.Empty).Replace("(", string.Empty).Replace(")", string.Empty).Replace(",", string.Empty).Replace("\"", string.Empty) : e.TestClassType.FullName;

                InitializeGridOptionsFromConfiguration(options, e.TestClassType, testName);
                InitializeCustomCodeOptions(options, e.TestClassType);
                var browserConfiguration = new BrowserConfiguration(executionType, currentLifecycle, currentBrowserType, currentBrowserSize, fullClassName, shouldCaptureHttpTraffic, shouldAutomaticallyScrollToVisible, options);
                e.Container.RegisterInstance(browserConfiguration, "_currentBrowserConfiguration");

                return(browserConfiguration);
            }
        }
Example #59
0
 public TestInitializeHook(BrowserType browser)
 {
     Browser = browser;
 }
Example #60
0
 public BaseClass(BrowserType browser) => _browserType = browser;