public void TestAndroidStitching() { ChromeOptions options = new ChromeOptions(); ChromeMobileEmulationDeviceSettings mobileSettings = new ChromeMobileEmulationDeviceSettings(); mobileSettings.PixelRatio = 4; mobileSettings.Width = 360; mobileSettings.Height = 740; mobileSettings.UserAgent = "Mozilla/5.0 (Linux; Android 8.0.0; SM-G960F Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.137 Mobile Safari/537.36"; options.EnableMobileEmulation(mobileSettings); IWebDriver driver = new ChromeDriver(options); driver.Url = "https://silko11dev.outsystems.net/TestApp_AUTO_OutSystemsUIMobile/Adaptive"; WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30)); wait.Until(ExpectedConditions.ElementIsVisible(By.CssSelector("#Columns2"))); Eyes eyes = new Eyes(); try { eyes.Open(driver, nameof(CustomerMobileTests), nameof(TestAndroidStitching)); IWebElement element = driver.FindElement(By.ClassName("content")); eyes.Check(Target.Region(element).Fully()); eyes.Close(); } finally { eyes.AbortIfNotClosed(); driver.Quit(); } }
public void Ticket31566_CVS_Mobile() { ChromeOptions options = new ChromeOptions(); ChromeMobileEmulationDeviceSettings mobileSettings = new ChromeMobileEmulationDeviceSettings(); mobileSettings.PixelRatio = 4; mobileSettings.Width = 360; mobileSettings.Height = 740; mobileSettings.UserAgent = "Mozilla/5.0 (Linux; Android 8.0.0; SM-G960F Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.137 Mobile Safari/537.36"; options.EnableMobileEmulation(mobileSettings); IWebDriver driver = new ChromeDriver(options); var eyes = new Eyes(); TestUtils.SetupLogging(eyes); try { eyes.Open(driver, "Demo C# app", "CVS Mobile"); eyes.StitchMode = StitchModes.Scroll; driver.Url = "https://www.cvs.com/mobile/mobile-cvs-pharmacy/"; eyes.Check("CVS!", Target.Window().Fully()); eyes.Close(); } finally { driver.Quit(); eyes.AbortIfNotClosed(); } }
static async Task <int> FacebookTool(CustomObj cookie, string username, string password, int threadSeq) { ChromeOptions op = new ChromeOptions(); var set = new ChromeMobileEmulationDeviceSettings(); set.Height = 350; set.Width = 219; set.PixelRatio = 2.0; set.UserAgent = "Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30"; set.EnableTouchEvents = true; op.EnableMobileEmulation(set); op.AddArgument("--disable-notifications"); op.AddArgument("--app=https://m.facebook.com"); op.AddExcludedArgument("enable-automation"); op.AddAdditionalCapability("useAutomationExtension", false); op.AddUserProfilePreference("credentials_enable_service", false); op.AddUserProfilePreference("profile.password_manager_enabled", false); op.AddArgument("window-size=234,350"); op.AddArgument("window-position=" + (-2 + threadSeq * 223) + ",7"); IWebDriver dr = new ChromeDriver(op); await Login(dr, cookie, username, password, threadSeq); return(1); }
/// <summary> /// Sets the mobile emulation settings for Chrome /// </summary> /// <param name="phoneType">The type of device to emulate</param> /// <param name="touchEvents">Whether to respond to touch events</param> /// <returns>The Chrome Mobile Emulation Device Settings</returns> private ChromeMobileEmulationDeviceSettings SetChromeMobileEmulationDeviceSettings(EnumPhoneType phoneType, bool touchEvents) { try { ChromeMobileEmulationDeviceSettings settings = new ChromeMobileEmulationDeviceSettings() { EnableTouchEvents = touchEvents, UserAgent = phoneType.ToString(), }; return(settings); } catch (Exception ex) { switch (BaseSettings.DebugLevel) { case EnumConsoleDebugLevel.Human: Console.Out.WriteLine("Unable to set Chrome Mobile Emulation settings."); Console.Out.WriteLine("Device Type: " + phoneType.ToString() + "| Touch Events: " + touchEvents.ToString()); break; case EnumConsoleDebugLevel.NotSpecified: case EnumConsoleDebugLevel.Message: Console.Out.WriteLine(ex.Message); break; case EnumConsoleDebugLevel.StackTrace: Console.Out.WriteLine(ex.Message); Console.Out.WriteLine(ex.StackTrace); break; } return(null); } }
private static ChromeOptions BuildChromeCapabilities( ChromeMobileEmulationDeviceSettings deviceSettings) { ChromeOptions chromeCapabilities = new ChromeOptions(); chromeCapabilities.EnableMobileEmulation(deviceSettings); return(chromeCapabilities); }
/// <summary> /// Sets the mobile emulation settings for Chrome from the app.config file /// </summary> /// <returns>The Chrome Mobile Emulation Device Settings</returns> private ChromeMobileEmulationDeviceSettings SetDefaultChromeMobileEmulationDeviceSettings() { try { string userAgent; bool.TryParse(Chrome.EnableTouchEvents, out bool touch); long.TryParse(Chrome.Height, out long height); double.TryParse(Chrome.PixelRatio, out double ratio); long.TryParse(Chrome.Width, out long width); ChromeMobileEmulationDeviceSettings settings = new ChromeMobileEmulationDeviceSettings(); userAgent = Chrome.UserAgent; settings.EnableTouchEvents = touch; settings.Height = height; settings.PixelRatio = ratio; if (userAgent.Length > 1) { settings.UserAgent = userAgent; } settings.Width = width; return(settings); } catch (Exception ex) { switch (BaseSettings.DebugLevel) { case EnumConsoleDebugLevel.Human: Console.Out.WriteLine("Driver was unable to load the mobile emulation settings."); Console.Out.WriteLine("Please investigate the changes you have made to your config file."); break; case EnumConsoleDebugLevel.NotSpecified: case EnumConsoleDebugLevel.Message: Console.Out.WriteLine(ex.Message); break; case EnumConsoleDebugLevel.StackTrace: Console.Out.WriteLine(ex.Message); Console.Out.WriteLine(ex.StackTrace); break; } ; return(null); } }
private static RemoteWebDriver StartChromeDriver(DriverSettings settings, MobileSettings mobile) { var options = new ChromeOptions(); settings.Capabilities?.ForEach(cap => options.AddAdditionalCapability(cap.Key, cap.Value)); if (!string.IsNullOrEmpty(settings.BrowserBinaryPath)) { options.BinaryLocation = settings.BrowserBinaryPath; } if (!string.IsNullOrEmpty(settings.Proxy)) { options.Proxy = new Proxy { HttpProxy = settings.Proxy } } ; if (settings.BrowserBinaryPath != null) { options.BinaryLocation = settings.BrowserBinaryPath; } if (settings.CmdArgs != null) { options.AddArguments(settings.CmdArgs); } if (settings.Extensions != null) { options.AddExtensions(settings.Extensions.Select(ext => ext.RelativeToBaseDirectory())); } settings.ProfilePrefs?.ForEach(pref => options.AddUserProfilePreference(pref.Key, pref.Value)); if (mobile != null && mobile.Enable) { if (!string.IsNullOrEmpty(mobile.DeviceName)) { options.EnableMobileEmulation(mobile.DeviceName); } else { var deviceSettings = new ChromeMobileEmulationDeviceSettings { EnableTouchEvents = mobile.EnableTouchEvents, Width = mobile.Width, Height = mobile.Height, PixelRatio = mobile.PixelRatio }; options.EnableMobileEmulation(deviceSettings); } } return(new ChromeDriver(options)); }
public MobileBrowserTests() { ChromeMobileEmulationDeviceSettings deviceSettings = new ChromeMobileEmulationDeviceSettings(); deviceSettings.Width = 1024; deviceSettings.Height = 1366; deviceSettings.UserAgent = "CustomDevice"; ChromeOptions chromeOpt = new ChromeOptions(); chromeOpt.EnableMobileEmulation(deviceSettings); setup = new DriverSetUp(); driver = new ChromeDriver(setup.ChromeDriverFolder, chromeOpt); element = new ElementHelper(driver); }
public ChromeOptions SetupChormeOption(int user_profile_path = 0, bool show_browser = false, string user_agent = "", int width = 0, int height = 0) { ChromeOptions option = new ChromeOptions(); if (!String.IsNullOrEmpty(user_agent)) { //V3.14 ChromeMobileEmulationDeviceSettings CMEDS = new ChromeMobileEmulationDeviceSettings(); //V4.0 //OpenQA.Selenium.Chromium.ChromiumMobileEmulationDeviceSettings CMEDS = new OpenQA.Selenium.Chromium.ChromiumMobileEmulationDeviceSettings(); CMEDS.Width = width > 0 ? width : 300; CMEDS.Height = height > 0 ? height : 500; CMEDS.PixelRatio = 1.0; if (!String.IsNullOrEmpty(user_agent)) { CMEDS.UserAgent = user_agent; } else { CMEDS.UserAgent = string.Empty; } option.EnableMobileEmulation(CMEDS); } option.AddArgument($@"user-data-dir={user_profile_path}"); option.AddArguments("--no-sandbox"); option.AddArguments("--start-maximized"); option.AddArguments("--disable-notifications"); option.AddArguments("--disable-gpu"); option.AddArguments("--disable-software-rasterizer"); option.AddArguments("--mute-audio"); option.AddArguments("--hide-scrollbars"); option.AddArgument("--disable-images"); option.AddArgument("--blink-settings=imagesEnabled=false"); option.AcceptInsecureCertificates = true; option.Proxy = null; #if !DEBUG if (!show_browser) { option.AddArgument("headless"); } #endif return(option); }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////// Функции для Запуска самого драйвера /////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Создаем экземпляр драйвера по заданным характеристикам , и после возвращаем его. //Функция для эмуляции драйвером айфона static IWebDriver Driver_Iphone() { ChromeOptions options_Mobile = new ChromeOptions(); //Загружаем характеристики ChromeMobileEmulationDeviceSettings settings = new ChromeMobileEmulationDeviceSettings(); settings.EnableTouchEvents = true; settings.Height = 640; settings.Width = 360; settings.PixelRatio = 3.0; settings.UserAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) CriOS/56.0.2924.75 Mobile Safari/535.19"; options_Mobile.EnableMobileEmulation(settings); //Пишем Обьект класса , который будет эмулировать окно браузера мобильной версии IWebDriver driver = new ChromeDriver(options_Mobile); // driver.Manage().Window.Maximize();// return(driver); }
public void DadaLargura993NaoDeveMostrarMenuMobile() { var deviceSettings = new ChromeMobileEmulationDeviceSettings(); deviceSettings.Width = 993; deviceSettings.Height = 800; deviceSettings.UserAgent = "Customizada"; var options = new ChromeOptions(); options.EnableMobileEmulation(deviceSettings); driver = new ChromeDriver(TestHelper.PastaDoExecutavel, options); var homePO = new HomeNaoLogadaPO(driver); homePO.Visitar(); Assert.False(homePO.Menu.MenuMobileVisivel); }
///// <summary> ///// Loads the Performance Logging Preferences for Chrome from the app.config file ///// </summary> //private void SetChromePerformanceLoggingPreferences() //{ // ChromePerformanceLoggingPreferences prefs = new ChromePerformanceLoggingPreferences(); // var buri = KVList["ChromePerformance_BufferUsageReportingInterval"].Value.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries); // prefs.BufferUsageReportingInterval = new TimeSpan(Convert.ToInt32(buri[0]), Convert.ToInt32(buri[1]), Convert.ToInt32(buri[2]), Convert.ToInt32(buri[3]), Convert.ToInt32(buri[4])); // prefs.IsCollectingNetworkEvents = Convert.ToBoolean(KVList["ChromePerformance_IsCollectingNetworkEvents"].Value); // prefs.IsCollectingPageEvents = Convert.ToBoolean(KVList["ChromePerformance_IsCollectingPageEvents"].Value); // prefs.IsCollectingTimelineEvents = Convert.ToBoolean(KVList["ChromePerformance_IsCollectingTimelineEvents"].Value); // LoggingPreferences = prefs; //} ///// <summary> ///// Adds a tracing category to the logging preferences for Chrome from the app.config file ///// </summary> //public void AddTracingCategoriesToLoggingPreferences() //{ // try // { // var categories = KVList["Chrome_TracingCategories"].Value.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries); // LoggingAddTracingCategories(categories); // } // catch (Exception ex) // { // Console.Out.WriteLine(ex.Message); // } //} public void AmendMobileEmulationForChrome(bool touchEvent, Int64 height, Int64 width, string userAgent, double pixelRatio) { try { bool.TryParse(Chrome.EnableTouchEvents, out bool touch); long.TryParse(Chrome.Height, out long h); long.TryParse(Chrome.Width, out long w); double.TryParse(Chrome.PixelRatio, out double pixel); ChromeMobileEmulationDeviceSettings settings = new ChromeMobileEmulationDeviceSettings() { EnableTouchEvents = touch, Height = h, PixelRatio = pixel, UserAgent = userAgent, Width = w }; } catch (Exception ex) { switch (BaseSettings.DebugLevel) { case EnumConsoleDebugLevel.Human: Console.Out.WriteLine("Driver was unable to load the mobile emulation settings."); Console.Out.WriteLine("Please investigate the changes you have made to your config file."); break; case EnumConsoleDebugLevel.NotSpecified: case EnumConsoleDebugLevel.Message: Console.Out.WriteLine(ex.Message); break; case EnumConsoleDebugLevel.StackTrace: Console.Out.WriteLine(ex.Message); Console.Out.WriteLine(ex.StackTrace); break; } } }
private static IWebDriver InitEyesSimulation_(string deviceName, string platformVersion, ScreenOrientation deviceOrientation, string platformName) { if (chromeSimulationData_ == null) { lock (lockObject_) { if (chromeSimulationData_ == null) { InitChromeSimulationData_(); } } } ChromeMobileEmulationDeviceSettings mobileSettings = chromeSimulationData_[$"{deviceName};{platformVersion};{deviceOrientation}"]; IWebDriver driver = null; if (mobileSettings != null) { ChromeOptions options = new ChromeOptions(); options.EnableMobileEmulation(mobileSettings); driver = CreateChromeDriver(options, headless: true); } return(driver); }
public void TestCheckRegion_LoadPageAfterOpen() { Eyes eyes = null; IWebDriver webDriver = null; try { ChromeMobileEmulationDeviceSettings mobileSettings = new ChromeMobileEmulationDeviceSettings() { UserAgent = "Mozilla/5.0 (Linux; Android 8.0.0; Android SDK built for x86_64 Build/OSR1.180418.004) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36", Width = 384, Height = 512, PixelRatio = 2 }; ChromeOptions chromeOptions = new ChromeOptions(); chromeOptions.EnableMobileEmulation(mobileSettings); webDriver = SeleniumUtils.CreateChromeDriver(chromeOptions); eyes = new Eyes(); Configuration configuration = eyes.GetConfiguration(); configuration.SetAppName(nameof(TestMobileEmulation)).SetTestName(nameof(TestCheckRegion_LoadPageAfterOpen)); eyes.SetConfiguration(configuration); eyes.Open(webDriver); webDriver.Url = "https://applitools.github.io/demo/TestPages/SpecialCases/hero.html"; eyes.Check(Target.Region(By.CssSelector("img")).Fully().WithName("Element outside the viewport")); eyes.Close(); } finally { eyes?.AbortIfNotClosed(); webDriver?.Quit(); } }
public static void Initialize(int deviceWidth = 400, int maxPageHeight = 4000, string userAgent = "Mozilla / 5.0(Linux; Android 5.0; SM - G900P Build / LRX21T) AppleWebKit / 537.36(KHTML, like Gecko) Chrome / 72.0.3604.0 Mobile Safari/ 537.36") { var options = new ChromeOptions(); options.AddArgument("headless"); options.AddArgument("no-sandbox"); options.AddArgument("disable-dev-shm-usage"); //options.AddArgument("log-level=3"); //options.AddArgument("silent"); deviceOptions = new ChromeMobileEmulationDeviceSettings(); deviceOptions.PixelRatio = 3; deviceOptions.Width = deviceWidth; deviceOptions.Height = maxPageHeight; deviceOptions.UserAgent = userAgent; options.EnableMobileEmulation(deviceOptions); options.SetLoggingPreference(LogType.Browser, LogLevel.Severe); var chromeDriverService = ChromeDriverService.CreateDefaultService(); chromeDriverService.HideCommandPromptWindow = true; chromeDriverService.SuppressInitialDiagnosticInformation = true; driver = new ChromeDriver(options); }
/// <summary> /// Gets the multi browser emulator web driver. /// </summary> /// <param name="testSettings">The test settings.</param> /// <param name="emulator">The emulator.</param> /// <param name="orientation">The device orientation.</param> /// <param name="testOutputHelper">The test output helper.</param> /// <returns></returns> public static ITestWebDriver InitializeMultiBrowserEmulatorDriver(TestSettings testSettings, Emulator emulator, DeviceOrientation orientation, ITestOutputHelper testOutputHelper) { ScreenShotCounter = 0; TestOutputHelper = testOutputHelper; testSettings.BrowserName = emulator + " " + orientation; testSettings = ValidateSavePaths(testSettings); //string driverLocation = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + // "\\MultiBrowser\\Drivers\\ChromeDrivers\\2.20\\chromedriver.exe"; string driverLocation = Path.Combine(AssemblyDirectory, "chromedriver.exe"); driverLocation = ValidateDriverPresentOrUnblocked(WebDriverType.ChromeDriver, driverLocation); var driverService = ChromeDriverService.CreateDefaultService(Path.GetDirectoryName(driverLocation), Path.GetFileName(driverLocation)); ValidateDriverPresentOrUnblocked(WebDriverType.ChromeDriver, driverLocation); var currentInstallPath = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\MultiBrowser", false) ?? Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Wow6432node\MultiBrowser", false); string installPathValue = null; if (currentInstallPath != null) { installPathValue = (string)currentInstallPath.GetValue("Path"); } if (installPathValue != null) { if (!installPathValue.EndsWith("\\")) { installPathValue = installPathValue + "\\"; } } #if DEBUG installPathValue = @"C:\Projects\MobileEmulator\bin\Debug\x64\"; #endif var options = new ChromeOptions { LeaveBrowserRunning = false, BinaryLocation = Path.Combine(installPathValue ?? @"C:\Program Files (x86)\MultiBrowser", "MultiBrowser Emulator.exe") }; var emulatorSettings = MultiBrowser.GetMultiBrowserEmulators(emulator); if (orientation == DeviceOrientation.Portrait) { var mobileEmulationSettings = new ChromeMobileEmulationDeviceSettings { UserAgent = emulatorSettings.DeviceUserAgent, Width = emulatorSettings.DeviceWidth, Height = emulatorSettings.DeviceHeight, EnableTouchEvents = true, PixelRatio = emulatorSettings.DevicePixelRatio }; options.EnableMobileEmulation(mobileEmulationSettings); //options.AddAdditionalCapability("mobileEmulation", new //{ // deviceMetrics = new // { // width = emulatorSettings.DeviceWidth, // height = emulatorSettings.DeviceHeight, // pixelRatio = emulatorSettings.DevicePixelRatio // }, // userAgent = emulatorSettings.DeviceUserAgent //}); } else { var mobileEmulationSettings = new ChromeMobileEmulationDeviceSettings { UserAgent = emulatorSettings.DeviceUserAgent, Width = emulatorSettings.DeviceHeight, Height = emulatorSettings.DeviceWidth, EnableTouchEvents = true, PixelRatio = emulatorSettings.DevicePixelRatio }; options.EnableMobileEmulation(mobileEmulationSettings); //options.AddAdditionalCapability("mobileEmulation", new //{ // deviceMetrics = new // { // width = emulatorSettings.DeviceHeight, // height = emulatorSettings.DeviceWidth, // pixelRatio = emulatorSettings.DevicePixelRatio // }, // userAgent = emulatorSettings.DeviceUserAgent //}); } #if DEBUG options.BinaryLocation = @"C:\Projects\MobileEmulator\bin\Debug\x64\MultiBrowser Emulator.exe"; #endif string authServerWhitelist = "auth-server-whitelist=" + testSettings.TestUri.Authority.Replace("www", "*"); string startUrl = "startUrl=" + testSettings.TestUri.AbsoluteUri; string selectedEmulator = "emulator=" + emulatorSettings.EmulatorArgument; var argsToPass = new[] { "test-type", "start-maximized", "no-default-browser-check", "allow-no-sandbox-job", "disable-component-update", "disable-translate", "disable-hang-monitor", authServerWhitelist, startUrl, selectedEmulator }; options.AddArguments(argsToPass); var driver = new ChromeDriver(driverService, options, testSettings.TimeoutTimeSpan); if (testSettings.DeleteAllCookies) { driver.Manage().Cookies.DeleteAllCookies(); } driver.Manage().Timeouts().ImplicitWait = testSettings.TimeoutTimeSpan; var extendedWebDriver = new TestWebDriver(driver, testSettings, TestOutputHelper); TestWebDriver = extendedWebDriver; return(extendedWebDriver); }
public static void Initialize(Browser browser, NUnit.Framework.TestContext testContext, bool headless = false) { //BrowserStack DesiredCapabilities capability = null; ChromeMobileEmulationDeviceSettings chromeMobileEmulationDeviceSettings = null; ChromeOptions chromeOptions = new ChromeOptions(); chromeOptions.AddArgument("--test-type"); chromeOptions.AddArgument("--disable-extensions"); InternetExplorerOptions ieOptions = new InternetExplorerOptions(); if (headless) { chromeOptions.AddArgument("--headless"); chromeOptions.AddArgument("--hide-scrollbars"); chromeOptions.AddArgument("--disable-gpu"); //headless_option.AddArgument("--remote-debugging-port=9222"); chromeOptions.BinaryLocation = string.Format(@"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"); } switch (browser) { case Browser.Chrome: chromeOptions.AddArgument("--test-type"); chromeOptions.AddArgument("--disable-extensions"); chromeOptions.AddArgument("start-maximized"); driver = new ChromeDriver(chromeOptions); Maximise(); break; case Browser.Chrome_1024x768: chromeMobileEmulationDeviceSettings = new ChromeMobileEmulationDeviceSettings(); chromeMobileEmulationDeviceSettings.Width = 1024; chromeMobileEmulationDeviceSettings.Height = 768; chromeMobileEmulationDeviceSettings.EnableTouchEvents = false; chromeMobileEmulationDeviceSettings.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36"; chromeOptions.EnableMobileEmulation(chromeMobileEmulationDeviceSettings); driver = new ChromeDriver(chromeOptions); Resize(1024, 768); break; case Browser.Chrome_1366x768: chromeMobileEmulationDeviceSettings = new ChromeMobileEmulationDeviceSettings(); chromeMobileEmulationDeviceSettings.Width = 1366; chromeMobileEmulationDeviceSettings.Height = 768; chromeMobileEmulationDeviceSettings.EnableTouchEvents = false; chromeMobileEmulationDeviceSettings.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36"; chromeOptions.EnableMobileEmulation(chromeMobileEmulationDeviceSettings); driver = new ChromeDriver(chromeOptions); Resize(1366, 768); break; case Browser.Chrome_Mobile: chromeOptions.EnableMobileEmulation("iPhone 6"); chromeOptions.AddArgument("--test-type"); chromeOptions.AddArgument("--disable-extensions"); driver = new ChromeDriver(chromeOptions); Resize(414, 736); break; case Browser.Chrome_Ipad: chromeMobileEmulationDeviceSettings = new ChromeMobileEmulationDeviceSettings(); chromeMobileEmulationDeviceSettings.Width = 768; chromeMobileEmulationDeviceSettings.Height = 1024; chromeMobileEmulationDeviceSettings.UserAgent = "Mozilla/5.0 (iPad; CPU OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1"; chromeOptions.EnableMobileEmulation(chromeMobileEmulationDeviceSettings); driver = new ChromeDriver(chromeOptions); Resize(768, 1024); break; case Browser.Chrome_Landscape_Ipad: chromeMobileEmulationDeviceSettings = new ChromeMobileEmulationDeviceSettings(); chromeMobileEmulationDeviceSettings.Width = 1024; chromeMobileEmulationDeviceSettings.Height = 768; chromeMobileEmulationDeviceSettings.UserAgent = "Mozilla/5.0 (iPad; CPU OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1"; chromeOptions.EnableMobileEmulation(chromeMobileEmulationDeviceSettings); driver = new ChromeDriver(chromeOptions); Resize(1024, 768); break; case Browser.PhantomJS: PhantomJSOptions optionsPJS = new PhantomJSOptions(); PhantomJSDriverService service = PhantomJSDriverService.CreateDefaultService(rootLocation); service.IgnoreSslErrors = true; service.AddArgument("logfile.txt 2>&1"); //optionsPJS.AddAdditionalCapability("phantomjs.page.settings.userAgent", "Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5355d Safari/8536.25"); DesiredCapabilities phantomCapabilites = DesiredCapabilities.PhantomJS(); optionsPJS.AddAdditionalCapability("phantomjs.page.settings.userAgent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:16.0) Gecko/20121026 Firefox/16.0"); //service.CookiesFile = "cookies.txt"; service.LocalStoragePath = rootLocation; driver = new PhantomJSDriver(service, optionsPJS, TimeSpan.FromMinutes(3.0)); break; case Browser.Firefox: driver = new FirefoxDriver(); break; case Browser.IE: var optionsIE = new InternetExplorerOptions { EnableNativeEvents = false }; driver = new InternetExplorerDriver(rootLocation, optionsIE); break; case Browser.Edge: var optionsEdge = new EdgeOptions(); optionsEdge.PageLoadStrategy = EdgePageLoadStrategy.Eager; driver = new EdgeDriver(rootLocation, optionsEdge); break; case Browser.BSIE9: capability = (DesiredCapabilities)ieOptions.ToCapabilities(); SetCapabilities(capability); capability.SetCapability("version", 9.0); capability.SetCapability("browser", "IE"); capability.SetCapability(CapabilityType.Platform, new Platform(PlatformType.Vista)); driver = new WebdriverExtensions.ScreenShotRemoteWebDriver(new Uri("http://hub.browserstack.com/wd/hub/"), capability); break; case Browser.BSIE10: capability = (DesiredCapabilities)ieOptions.ToCapabilities(); SetCapabilities(capability); SetCapabilities(capability); capability.SetCapability("browser", "IE"); capability.SetCapability("version", 10.0); driver = new WebdriverExtensions.ScreenShotRemoteWebDriver(new Uri("http://hub.browserstack.com/wd/hub/"), capability); break; case Browser.BSIE11: capability = (DesiredCapabilities)ieOptions.ToCapabilities(); SetCapabilities(capability); capability.SetCapability("browser", "IE"); capability.SetCapability("version", 11.0); capability.SetCapability(CapabilityType.Platform, "Win8"); driver = new WebdriverExtensions.ScreenShotRemoteWebDriver(new Uri("http://hub.browserstack.com/wd/hub/"), capability); break; } explicitlyWait = new WebDriverWait(driver, TimeSpan.FromSeconds(5)); }
public void YeezysTest() { Eyes eyes = new Eyes(); TestUtils.SetupLogging(eyes); //ChromeOptions options = new ChromeOptions(); //options.AddArguments("ignore-certificate-errors"); //string browserstackURL = "https://hub-cloud.browserstack.com/wd/hub"; //DesiredCapabilities capabilities = new DesiredCapabilities(); //Dictionary<string, object> browserstackOptions = new Dictionary<string, object>(); //browserstackOptions.Add("osVersion", "9.0"); //browserstackOptions.Add("deviceName", "Google Pixel 3 XL"); //browserstackOptions.Add("realMobile", "true"); //browserstackOptions.Add("local", "false"); //browserstackOptions.Add("userName", Environment.GetEnvironmentVariable("BROWSERSTACK_USERNAME")); //browserstackOptions.Add("accessKey", Environment.GetEnvironmentVariable("BROWSERSTACK_ACCESS_KEY")); //capabilities.SetCapability("bstack:options", browserstackOptions); //IWebDriver driver = new RemoteWebDriver(new Uri(browserstackURL), capabilities); ChromeMobileEmulationDeviceSettings mobileSettings = new ChromeMobileEmulationDeviceSettings() { UserAgent = "Mozilla/5.0 (Linux; Android 9; Pixel 3 XL) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.99 Mobile Safari/537.36", Width = 412, Height = 693, PixelRatio = 3.5 }; ChromeOptions chromeOptions = new ChromeOptions(); chromeOptions.EnableMobileEmulation(mobileSettings); IWebDriver driver = new ChromeDriver(chromeOptions); try { Configuration config = new Configuration(); config.SetAppName("Zach's Demo c# App"); //config.setViewportSize(new RectangleSize(1600, 900)); config.SetTestName("YEEEZY"); //config.setForceFullPageScreenshot(true); //config.setApiKey(System.getenv("APPLITOOLS_API_KEY_BUG")); eyes.SetConfiguration(config); //eyes.HideScrollbars = false; //eyes.HideCaret = false; eyes.SendDom = false; eyes.MatchTimeout = new TimeSpan(0); //eyes.setForceFullPageScreenshot(true); //eyes.SetSaveDebugScreenshots(true); eyes.StitchMode = StitchModes.CSS; driver = eyes.Open(driver); driver.Url = "https://www.adidas.co.uk/yeezy"; //eyes.Check(Target.Window().Fully()); eyes.Check(Target.Region(By.CssSelector(".theme-light")).ScrollRootElement(By.CssSelector("#app")).Fully()); eyes.Close(); } finally { driver?.Quit(); eyes.AbortIfNotClosed(); } }
public ChromeResponsiveDriver(ChromeMobileEmulationDeviceSettings deviceSettings) : base(BuildChromeCapabilities(deviceSettings)) { }
public override IWebDriver CreateDriver(DriverProperty driverProperty) { ParameterValidator.ValidateNotNull(driverProperty, "Driver Property"); ChromeOptions options = new ChromeOptions(); if (driverProperty.Headless) { options.AddArgument("--headless"); options.AddArgument("--disable-gpu"); options.AddUserProfilePreference("disable-popup-blocking", "true"); options.AddUserProfilePreference("intl.accept_languages", "en,en_US"); } if (driverProperty.DownloadLocation != null) { options.AddUserProfilePreference("download.default_directory", driverProperty.DownloadLocation); } if (driverProperty.Arguments != null) { options.AddArguments(driverProperty.GetArgumentsAsArray()); } if (DriverVersion == null) { lock (Instancelock) { if (DriverVersion == null) { if (string.IsNullOrEmpty(driverProperty.DriverVersion)) { DriverVersion = GetStableVersion(); } else { DriverVersion = driverProperty.DriverVersion; } } } } // Use custom Chrome binary (81) // https://chromium.cypress.io/win64/stable/81.0.4044.92 // options.BinaryLocation = "C:\\Users\\sbaltuonis\\Downloads\\chrome-win\\chrome.exe"; // Run in private mode options.AddArgument("--incognito"); // Enable mobile emulation if (!string.IsNullOrEmpty(driverProperty.DeviceName)) { options.EnableMobileEmulation(driverProperty.DeviceName); } else if (!string.IsNullOrEmpty(driverProperty.CustomUserAgent)) { if (driverProperty.CustomWidth <= 0 || driverProperty.CustomHeight <= 0 || driverProperty.CustomPixelRatio <= 0) { throw new Exception("Custom device width, height and pixel ratio must be greater than 0"); } ChromeMobileEmulationDeviceSettings emulationSettings = new ChromeMobileEmulationDeviceSettings { UserAgent = driverProperty.CustomUserAgent, Width = driverProperty.CustomWidth, Height = driverProperty.CustomHeight, PixelRatio = driverProperty.CustomPixelRatio }; options.EnableMobileEmulation(emulationSettings); } // Setup driver binary try { new WebDriverManager.DriverManager().SetUpDriver(new ChromeConfig(), DriverVersion); } catch (Exception) { throw new Exception($"Cannot get Chrome driver version {DriverVersion}"); } #pragma warning disable CA2000 // Dispose objects before losing scope return(new ChromeDriver(ChromeDriverService.CreateDefaultService(), options, TimeSpan.FromSeconds(180))); #pragma warning restore CA2000 // Dispose objects before losing scope }
public ChromeOptions SetupChormeOption(string user_profile_path = "", string default_download_folder = "", string user_agent = "", bool disable_img = true, bool show_browser = false, int width = 0, int height = 0) { ChromeOptions option = new ChromeOptions(); if (!String.IsNullOrEmpty(user_agent) && width < 800) { ChromeMobileEmulationDeviceSettings CMEDS = new ChromeMobileEmulationDeviceSettings(); //OpenQA.Selenium.Chromium.ChromiumMobileEmulationDeviceSettings CMEDS = new OpenQA.Selenium.Chromium.ChromiumMobileEmulationDeviceSettings(); CMEDS.Width = width > 0 ? width : 300; CMEDS.Height = height > 0 ? height : 500; CMEDS.PixelRatio = 1.0; if (!String.IsNullOrEmpty(user_agent)) { CMEDS.UserAgent = user_agent; } else { CMEDS.UserAgent = string.Empty; } option.EnableMobileEmulation(CMEDS); } else { if (width > 0) { option.AddArguments($"--width={width}"); } if (height > 0) { option.AddArguments($"--height={height}"); } } if (!String.IsNullOrEmpty(user_profile_path)) { option.AddArguments($@"user-data-dir={user_profile_path}"); } option.AddExcludedArgument("enable-automation"); //option.AddAdditionalCapability("excludeSwitches", "enable-automation"); option.AddArgument("-disable-notifications"); option.AddArguments("--no-sandbox"); option.AddArguments("--disable-infobars"); //https://stackoverflow.com/a/43840128/1689770 option.AddArguments("--disable-dev-shm-usage"); //https://stackoverflow.com/a/50725918/1689770 option.AddArguments("--disable-browser-side-navigation"); //https://stackoverflow.com/a/49123152/1689770 option.AddArguments("--disable-gpu"); option.AddArguments("start-maximized"); option.AddArguments("--disable-notifications"); option.AddArguments("--disable-software-rasterizer"); option.AddArguments("--mute-audio"); option.AddArguments("enable-features=NetworkServiceInProcess"); option.PageLoadStrategy = PageLoadStrategy.Eager; //option.AddArguments("disable-features=NetworkService"); if (disable_img) { option.AddArgument("--disable-images"); option.AddArgument("--blink-settings=imagesEnabled=false"); } option.AcceptInsecureCertificates = true; option.Proxy = null; option.AddArguments("chrome.switches", "-disable-extensions"); option.AddUserProfilePreference("exit_type", "none"); option.AddUserProfilePreference("exited_cleanly", "true"); option.AddArgument("--disable-features=InfiniteSessionRestore"); if (!string.IsNullOrEmpty(default_download_folder)) { option.AddUserProfilePreference("download.default_directory", $"{default_download_folder}"); } option.AddUserProfilePreference("download.prompt_for_download", false); option.AddUserProfilePreference("disable-popup-blocking", "true"); if (!show_browser) { option.AddArgument("headless"); } return(option); }
public void initBrowser(bool Clean, Enum pBrowserType) { try { eCommSite.SolutionsPrime.spWrapper.ProjectDetails["TestResultFolder"] = RunTestContext.TestRunDirectory + "-PICS"; if (!System.IO.Directory.Exists(ProjectDetails["TestResultFolder"])) { System.IO.Directory.CreateDirectory(ProjectDetails["TestResultFolder"]); } } catch { Console.WriteLine("In Catch Block ==" + ProjectDetails["TestResultFolder"]); } if (ProjectDetails["BrowserInitiated"].Equals("false")) { switch (pBrowserType.ToString()) { case "FireFox": if (Clean) { KillProcess("geckodriver"); KillProcess("firefox"); } profile = new FirefoxProfile();; profile.SetPreference("geo.prompt.testing", true); profile.SetPreference("geo.prompt.testing.allow", true); profile.SetPreference("geo.enabled", true); profile.SetPreference("geo.provider.ms-windows-location", true); profile.SetPreference("geo.wifi.uri", "{ \"status\": \"OK\", \"accuracy\": 10.0, \"location\": { \"lat\": 50.850780, \"lng\": 4.358138, \"latitude\": 50.850780, \"longitude\": 4.358138, \"accuracy\": 10.0}}"); //driver = new FirefoxDriver(profile); driver = new FirefoxDriver(); ProjectDetails["BrowserType"] = "1"; driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5); //driver.Navigate().GoToUrl(ProjectDetails["BaseStateURL"]); //driver.Manage().Window.Maximize(); break; case "IE": if (Clean) { KillProcess("IEDriverServer"); KillProcess("iexplore"); } InternetExplorerOptions ieo = new InternetExplorerOptions(); ieo.IntroduceInstabilityByIgnoringProtectedModeSettings = true; ieo.IgnoreZoomLevel = true; ieo.InitialBrowserUrl = ProjectDetails["BaseStateURL"]; ieo.EnsureCleanSession = true; driver = new InternetExplorerDriver(strLocationIE, ieo); driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5); ProjectDetails["BrowserType"] = "2"; //driver.Navigate().GoToUrl(ProjectDetails["BaseStateURL"]); //driver.Manage().Window.Maximize(); break; case "Chrome": if (Clean) { KillProcess("chromedriver"); KillProcess("chrome"); } ChromeOptions co = new ChromeOptions(); co.AddArgument("--incognito"); driver = new ChromeDriver(strLocationChrome, co); driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5); driver.Navigate().GoToUrl(ProjectDetails["BaseStateURL"]); ProjectDetails["BrowserType"] = "3"; driver.Manage().Window.Maximize(); break; case "ChromeMobile": if (Clean) { KillProcess("chromedriver"); KillProcess("chrome"); } ChromeOptions com = new ChromeOptions(); com.AddArgument("--incognito"); com.AddArgument("--use-mobile-user-agent"); ChromeMobileEmulationDeviceSettings cmed = new ChromeMobileEmulationDeviceSettings("Apple iPad"); cmed.PixelRatio = 2.0; cmed.Height = 1024; cmed.Width = 768; com.EnableMobileEmulation(cmed); driver = new ChromeDriver(strLocationChrome, com); driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5); driver.Navigate().GoToUrl(ProjectDetails["BaseStateURL"]); ProjectDetails["BrowserType"] = "3"; driver.Manage().Window.Maximize(); break; default: driver = new FirefoxDriver(); driver.Manage().Window.Maximize(); ProjectDetails["BrowserType"] = "1"; break; } ProjectDetails["BrowserInitiated"] = "true"; } }