/// <summary>
        /// Executes a command
        /// </summary>
        /// <param name="commandToExecute">The command you wish to execute</param>
        /// <returns>A response from the browser</returns>
        public Response Execute(Command commandToExecute)
        {
            Response toReturn = null;

            if (commandToExecute.Name == DriverCommand.NewSession)
            {
                this.server.Start();
                this.internalExecutor = new HttpCommandExecutor(this.server.ExtensionUri, this.commandTimeout);
            }

            // Use a try-catch block to catch exceptions for the Quit
            // command, so that we can get the finally block.
            try
            {
                toReturn = this.internalExecutor.Execute(commandToExecute);
            }
            finally
            {
                if (commandToExecute.Name == DriverCommand.Quit)
                {
                    this.server.Dispose();
                }
            }

            return(toReturn);
        }
Example #2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ExtensionConnection"/> class.
        /// </summary>
        /// <param name="lockObject">An <see cref="ILock"/> object used to lock the mutex port before connection.</param>
        /// <param name="binary">The <see cref="FirefoxBinary"/> on which to make the connection.</param>
        /// <param name="profile">The <see cref="FirefoxProfile"/> creating the connection.</param>
        /// <param name="host">The name of the host on which to connect to the Firefox extension (usually "localhost").</param>
        public ExtensionConnection(ILock lockObject, FirefoxBinary binary, FirefoxProfile profile, string host)
        {
            this.profile = profile;
            if (binary == null)
            {
                this.process = new FirefoxBinary();
            }
            else
            {
                this.process = binary;
            }

            lockObject.LockObject(this.process.TimeoutInMilliseconds);
            try
            {
                int portToUse = DetermineNextFreePort(host, profile.Port);

                profile.Port = portToUse;
                profile.UpdateUserPreferences();
                this.process.Clean(profile);
                this.process.StartProfile(profile, null);

                this.SetAddress(host, portToUse);

                // TODO (JimEvans): Get a better url algorithm.
                this.executor = new HttpCommandExecutor(new Uri(string.Format(CultureInfo.InvariantCulture, "http://{0}:{1}/hub/", host, portToUse)));
            }
            finally
            {
                lockObject.UnlockObject();
            }
        }
        /// <summary>
        /// Starts the connection to the extension.
        /// </summary>
        public void Start()
        {
            using (ILock lockObject = new SocketLock(this.profile.Port - 1))
            {
                lockObject.LockObject(this.process.TimeoutInMilliseconds);
                try
                {
                    int portToUse = DetermineNextFreePort(this.host, this.profile.Port);
                    this.profile.Port = portToUse;
                    this.profile.WriteToDisk();
                    this.process.Clean(this.profile);
                    this.process.StartProfile(this.profile, new string[] { "-foreground" });

                    this.SetAddress(portToUse);

                    // TODO (JimEvans): Get a better url algorithm.
                    this.executor = new HttpCommandExecutor(new Uri(string.Format(CultureInfo.InvariantCulture, "http://{0}:{1}/hub/", this.host, portToUse)), this.timeout);
                }
                finally
                {
                    lockObject.UnlockObject();
                }
            }

            this.ConnectToBrowser(this.process.TimeoutInMilliseconds);
        }
        public Response Execute(Command commandToExecute)
        {
            if (commandToExecute == null)
            {
                throw new ArgumentNullException("commandToExecute", "Command may not be null");
            }
            Response result = null;

            if (commandToExecute.Name == DriverCommand.NewSession)
            {
                this.server.Start();
                this.internalExecutor = new HttpCommandExecutor(this.server.ExtensionUri, this.commandTimeout);
            }
            try
            {
                result = this.internalExecutor.Execute(commandToExecute);
            }
            finally
            {
                if (commandToExecute.Name == DriverCommand.Quit)
                {
                    this.Dispose();
                }
            }
            return(result);
        }
        /// <summary>
        /// Execute Server Command
        /// </summary>
        /// <param name="commandToExecute">Command to execute</param>
        /// <param name="@params">parameters for the command</param>
        /// <param name="throwOnFailure">throw on command failure, default true</param>
        /// <typeparam name="T">type of the result expected</typeparam>
        /// <returns></returns>
        public Response Execute(string commandToExecute, Dictionary <string, object> @params = null, bool throwOnFailure = true)
        {
            Helper.IsNullOrEmpty(serverUri, $"{nameof(serverUri)} is empty");
            Helper.IsNullOrEmpty(sessionId, $"{nameof(sessionId)} is empty");
            if (string.IsNullOrEmpty(commandToExecute))
            {
                throw new ArgumentNullException($"[{nameof(commandToExecute)}] cannot be null or empty.");
            }
            Response response = null;

            using (HttpCommandExecutor executor = new HttpCommandExecutor(serverUri, TimeSpan.FromSeconds(timeoutInSeconds))) {
                Command cmd = new Command(sessionId, commandToExecute, @params);
                if (executor.CommandInfoRepository.GetCommandInfo(commandToExecute) == null)
                {
                    throw new NotSupportedException($"Command [{commandToExecute}] is not supported with Appium/Selenium APIs.");
                }
                try {
                    response = executor.Execute(cmd);
                } catch (Exception e) {
                    if (throwOnFailure)
                    {
                        throw new WebDriverException($"Execution of Command [{commandToExecute}] with parameters [{string.Join(',', @params.Values) ?? string.Empty}] failed!!.Exception:\n:{e}");
                    }
                }
            }

            if (response == null || response.Value == null)
            {
                return(null);
            }
            return(response);
        }
Example #6
0
        static void Main(string[] args)
        {
            Console.WriteLine("Starting test...");
            HttpCommandExecutor executor = new HttpCommandExecutor();

            // If you're absolutely convinced that the problem is that the code
            // is using HttpWebRequest/HttpWebResponse instead of System.Net.Http.HttpClient,
            // you can uncomment the following line of code instead of the one
            // immediately above. It makes no difference.
            //HttpCommandExecutor executor = new AlternativeHttpCommandExecutor();

            executor.StartServer();
            string sessionId = StartSession(executor);

            NavigateToUrl(executor, sessionId, "http://www.google.com");

            Console.WriteLine("Making 10 HTTP calls to localhost, logging the elapsed time...");
            for (int i = 0; i < 10; i++)
            {
                GetPageTitle(executor, sessionId);
            }

            Console.WriteLine("Test finished. Press <Enter> to exit.");
            Console.ReadLine();
            StopSession(executor, sessionId);
            executor.StopServer();
        }
Example #7
0
        private static void StopSession(HttpCommandExecutor executor, string sessionId)
        {
            Console.WriteLine("Ending session {0}", sessionId);
            Uri    startSessionUri = new Uri(string.Format("http://localhost:9515/session/{0}", sessionId));
            string response        = executor.MakeHttpRequest(startSessionUri, "DELETE", string.Empty);

            Console.WriteLine(response);
        }
Example #8
0
        private static void NavigateToUrl(HttpCommandExecutor executor, string sessionId, string url)
        {
            Console.WriteLine("Navigating to {0}", url);
            Uri    startSessionUri = new Uri(string.Format("http://localhost:9515/session/{0}/url", sessionId));
            string response        = executor.MakeHttpRequest(startSessionUri, "POST", string.Format("{{ \"url\": \"{0}\" }}", url));

            Console.WriteLine("Navigation complete");
        }
Example #9
0
        private static string StartSession(HttpCommandExecutor executor)
        {
            Uri      startSessionUri = new Uri("http://localhost:9515/session");
            string   rawResponse     = executor.MakeHttpRequest(startSessionUri, "POST", "{\"desiredCapabilities\": { \"browserName\": \"chrome\" } }");
            Response response        = JsonConvert.DeserializeObject <Response>(rawResponse);

            Console.WriteLine("Started session {0}", response.SessionId);
            return(response.SessionId);
        }
Example #10
0
        private static void GetPageTitle(HttpCommandExecutor executor, string sessionId)
        {
            Uri startSessionUri = new Uri(string.Format("http://localhost:9515/session/{0}/title", sessionId));

            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            string response = executor.MakeHttpRequest(startSessionUri, "GET", string.Empty);

            stopwatch.Stop();
            Console.WriteLine("Elapsed time for HTTP call: {0} milliseconds", stopwatch.ElapsedMilliseconds);
        }
Example #11
0
        static void Main(string[] args)
        {
            Console.WriteLine("Starting test...");
            HttpCommandExecutor executor = new HttpCommandExecutor();

            executor.StartServer();
            string sessionId = StartSession(executor);

            NavigateToUrl(executor, sessionId, "http://www.google.com");

            Console.WriteLine("Making 10 HTTP calls to localhost, logging the elapsed time...");
            for (int i = 0; i < 10; i++)
            {
                GetPageTitle(executor, sessionId);
            }

            Console.WriteLine("Test finished. Press <Enter> to exit.");
            Console.ReadLine();
            StopSession(executor, sessionId);
            executor.StopServer();
        }
Example #12
0
        public void AddNumbers()
        {
            ChromeOptions       options         = new ChromeOptions();
            var                 p               = new WebProxy("http://*****:*****@ng-model='first']"));
            var secondNumber = driver.FindElement(By.XPath("//input[@ng-model='second']"));
            var goButton     = driver.FindElement(By.Id("gobutton"));

            firstNumber.SendKeys("1");
            secondNumber.SendKeys("2");
            goButton.Click();
            Thread.Sleep(3000);
            var latestResult = driver.FindElement(By.XPath("(//tr[1]/td[last()])")).Text;

            Assert.AreEqual("3", latestResult);
            driver.Close();
        }
Example #13
0
        protected static IFlutterDriver StartApplication()
        {
            if (!System.IO.File.Exists(AndroidAppPath))
            {
                throw new System.IO.FileNotFoundException($"To run the system tests, you need the sample app at '{AndroidAppPath}'. See the README.md file for more information. ");
            }

            var capabilities = new AppiumOptions();

            // Emulator and App Path
            capabilities.AddAdditionalCapability(MobileCapabilityType.Udid, "emulator-5554");
            capabilities.AddAdditionalCapability(MobileCapabilityType.App, AndroidAppPath);

            // Other stuff
            capabilities.AddAdditionalCapability(MobileCapabilityType.DeviceName, "Pixel 2");
            capabilities.AddAdditionalCapability(MobileCapabilityType.PlatformName, "Android");
            capabilities.AddAdditionalCapability(MobileCapabilityType.PlatformVersion, "10");
            capabilities.AddAdditionalCapability(AndroidMobileCapabilityType.NativeWebScreenshot, false);
            capabilities.AddAdditionalCapability("buildToolsVersion", "28.0.3");
            capabilities.AddAdditionalCapability("uiautomator2ServerInstallTimeout", 60000);
            capabilities.AddAdditionalCapability("uiautomator2ServerLaunchTimeout", 60000);
            capabilities.AddAdditionalCapability("adbExecTimeout", 60000);
            capabilities.AddAdditionalCapability(MobileCapabilityType.AutomationName, "Flutter");
            capabilities.AddAdditionalCapability(MobileCapabilityType.NoReset, false);
            capabilities.AddAdditionalCapability(MobileCapabilityType.NewCommandTimeout, ReadEnvironmentVariable("TESTAPP_MOBILECAPABILITYTYPE_NEWCOMMANDTIMEOUT", orFallbackTo: 60000));

            // TODO:
            var addressOfRemoteServer = new Uri("http://127.0.0.1:4723/wd/hub");
            var commandExecutor       = new HttpCommandExecutor(addressOfRemoteServer, TimeSpan.FromSeconds(ReadEnvironmentVariable("TESTAPP_HTTPEXECUTOR_TIMEOUT_IN_SECONDS", orFallbackTo: 60)));
            var webDriver             = new AndroidDriver <IWebElement>(commandExecutor, capabilities);

            // NOTE: ElementTimeoutInSeconds is the default only for WaitFor and WaitForAbsent at the moment
            var fd = new FlutterDriver(webDriver, commandExecutor, elementTimeoutInSeconds: 30);

            return(fd);
        }
Example #14
0
        public static IWebDriver SetupWebdriver(string browserName, string env, string operatingSystem,
                                                string buldName, string vrsion, string testCaseName, bool localRun)
        {
            #region Get Parameters

            // Get from TestContext
            string browser          = browserName;
            string environment      = env;
            string os               = operatingSystem;
            string buildName        = buldName;
            string version          = vrsion;
            string testName         = testCaseName;
            bool   isLocalExecution = localRun;

            // Get from Configuration file
            //string userName = CommonMethods.Get_JsonAttribute("Configuration.json", "SauceLabsCredentials.User", isInputFile: false).ToString();
            //string accessKey = CommonMethods.Get_JsonAttribute("Configuration.json", "SauceLabsCredentials.AccessKey", isInputFile: false).ToString();
            //string parentTunnel = CommonMethods.Get_JsonAttribute("Configuration.json", "SauceLabsCredentials.ParentTunnel", isInputFile: false).ToString();
            //string remoteURL = CommonMethods.Get_JsonAttribute("Configuration.json", "SauceLabsCredentials.RemoteURL", isInputFile: false).ToString();
            //string proxyURL = CommonMethods.Get_JsonAttribute("Configuration.json", "SauceLabsCredentials.ProxyURL", isInputFile: false).ToString();
            string userName     = string.Empty;
            string accessKey    = string.Empty;
            string parentTunnel = string.Empty;
            string remoteURL    = string.Empty;
            string proxyURL     = string.Empty;
            #endregion

            IWebDriver          driver;
            HttpCommandExecutor executor = new HttpCommandExecutor(new Uri(remoteURL), TimeSpan.FromSeconds(120), false)
            {
                Proxy = new WebProxy(new Uri(proxyURL))
            };

            switch (browser)
            {
            case "InternetExplorer":
                if (isLocalExecution)
                {
                    driver = new InternetExplorerDriver(Environment.CurrentDirectory, new InternetExplorerOptions(), TimeSpan.FromSeconds(300));
                    break;
                }

                InternetExplorerOptions ieOptions = new InternetExplorerOptions();
                ieOptions.AddAdditionalCapability("username", userName, true);
                ieOptions.AddAdditionalCapability("accessKey", accessKey, true);
                ieOptions.AddAdditionalCapability("parentTunnel", parentTunnel, true);
                ieOptions.AddAdditionalCapability("platform", os, true);
                ieOptions.AddAdditionalCapability("tunnelIdentifier", environment, true);
                ieOptions.AddAdditionalCapability("name", testName, true);
                ieOptions.AddAdditionalCapability("build", buildName, true);
                ieOptions.AddAdditionalCapability("version", version, true);
                driver = new RemoteWebDriver(executor, ieOptions.ToCapabilities());
                break;

            case "Edge":
                if (isLocalExecution)
                {
                    driver = new EdgeDriver(Environment.CurrentDirectory, new EdgeOptions(), TimeSpan.FromSeconds(300));
                    break;
                }

                EdgeOptions edgeOptions = new EdgeOptions();
                edgeOptions.AddAdditionalCapability("username", userName);
                edgeOptions.AddAdditionalCapability("accessKey", accessKey);
                edgeOptions.AddAdditionalCapability("parentTunnel", parentTunnel);
                edgeOptions.AddAdditionalCapability("platform", os);
                edgeOptions.AddAdditionalCapability("tunnelIdentifier", environment);
                edgeOptions.AddAdditionalCapability("name", testName);
                edgeOptions.AddAdditionalCapability("build", buildName);
                edgeOptions.AddAdditionalCapability("version", version);
                driver = new RemoteWebDriver(executor, edgeOptions.ToCapabilities());
                break;

            case "Firefox":
                if (isLocalExecution)
                {
                    driver = new FirefoxDriver(Environment.CurrentDirectory, new FirefoxOptions(), TimeSpan.FromSeconds(300));
                    break;
                }

                FirefoxOptions firefoxOptions = new FirefoxOptions();
                firefoxOptions.AddAdditionalCapability("username", userName, true);
                firefoxOptions.AddAdditionalCapability("accessKey", accessKey, true);
                firefoxOptions.AddAdditionalCapability("parentTunnel", parentTunnel, true);
                firefoxOptions.AddAdditionalCapability("platform", os, true);
                firefoxOptions.AddAdditionalCapability("tunnelIdentifier", environment, true);
                firefoxOptions.AddAdditionalCapability("name", testName, true);
                firefoxOptions.AddAdditionalCapability("build", buildName, true);
                firefoxOptions.AddAdditionalCapability("version", version, true);
                driver = new RemoteWebDriver(executor, firefoxOptions.ToCapabilities());
                break;

            default:
                if (isLocalExecution)
                {
                    //ChromeOptions chromeOptions1 = new ChromeOptions();
                    //chromeOptions1.EnableMobileEmulation("Galaxy S5");
                    //driver = new ChromeDriver(Environment.CurrentDirectory, chromeOptions1, TimeSpan.FromSeconds(300));
                    driver = new ChromeDriver(Environment.CurrentDirectory, new ChromeOptions(), TimeSpan.FromSeconds(300));
                    break;
                }

                ChromeOptions chromeOptions = new ChromeOptions();
                chromeOptions.AddAdditionalCapability("username", userName, true);
                chromeOptions.AddAdditionalCapability("accessKey", accessKey, true);
                chromeOptions.AddAdditionalCapability("parentTunnel", parentTunnel, true);
                chromeOptions.AddAdditionalCapability("platform", os, true);
                chromeOptions.AddAdditionalCapability("tunnelIdentifier", environment, true);
                chromeOptions.AddAdditionalCapability("name", testName, true);
                chromeOptions.AddAdditionalCapability("build", buildName, true);
                chromeOptions.AddAdditionalCapability("version", version, true);
                driver = new RemoteWebDriver(executor, chromeOptions.ToCapabilities());
                break;
            }

            driver.Manage().Window.Maximize();
            return(driver);
        }
Example #15
0
        public static void Initialize(ILogger bootstrappingLogger, string prefix, Action <string, IServiceCollection, ITestRunReporterContext> beforeContainerBuild)
        {
            if (_instance != null)
            {
                throw new InvalidOperationException($"The Initialize method has already been called. ");
            }
            if (prefix == null)
            {
                throw new ArgumentNullException(nameof(prefix));
            }
            if (beforeContainerBuild == null)
            {
                throw new ArgumentNullException(nameof(beforeContainerBuild));
            }

            Environment.SetEnvironmentVariable("TEST_OUTPUT_FOLDER", Directory.GetCurrentDirectory(), EnvironmentVariableTarget.Process);
            Environment.SetEnvironmentVariable("TEST_DEPLOYMENT_FOLDER", Directory.GetCurrentDirectory(), EnvironmentVariableTarget.Process);

            //
            // TODO: When this gets too big, look at Factories
            //

            var services = new ServiceCollection();

            RegisterDeviceSettings(bootstrappingLogger, prefix, services);
            RegisterBrowserSettings(bootstrappingLogger, prefix, services);

            var instrumentationSettings = ConfigureSettings <IInstrumentationSettings, InstrumentationSettings>(bootstrappingLogger, prefix, "InstrumentationSettings", "common.json", "instrumentationSettings", services);

            RegisterSettings <RemoteWebDriverSettings>(bootstrappingLogger, prefix, "RemoteWebDriverSettings", "common-localhost-selenium.json", "remoteWebDriverSettings", services, registerInstance: true);
            RegisterSettings <EnvironmentSettings>(bootstrappingLogger, prefix, "EnvironmentSettings", "internet.json", "environmentSettings", services, registerInstance: true);
            ConfigureSettings <IControlSettings, ControlSettings>(bootstrappingLogger, prefix, "ControlSettings", "common.json", "controlSettings", services);

            // Clear the variables so they do not creep into the rest of our implementation
            Environment.SetEnvironmentVariable("TEST_OUTPUT_FOLDER", null, EnvironmentVariableTarget.Process);
            Environment.SetEnvironmentVariable("TEST_DEPLOYMENT_FOLDER", null, EnvironmentVariableTarget.Process);

            // Singletons: statics that are instantiated once for the lifetime of the entire test run
            services.AddSingleton <IDriverSessionFactory, DriverSessionFactory>();

            var testRunReporterContext = new TestRunReporterContext()
            {
                InstrumentationSettings = instrumentationSettings,
                RootReportingFolder     = instrumentationSettings.RootReportingFolder,
                TestRunIdentity         = DateTime.Now.ToString("yyyyMMdd-HHmmss")
            };

            services.AddSingleton <ITestRunReporterContext>(testRunReporterContext);

            // Scoped: per test
            services.AddScoped(isp =>
            {
                var serilogContext = BuildSerilogConfiguration();

                var logPath = isp.GetRequiredService <ITestCaseReporterContext>().LogFilePath;

                LoggerConfiguration loggerConfiguration = new LoggerConfiguration()
                                                          .ReadFrom
                                                          .Configuration(serilogContext)
                                                          .Enrich
                                                          .FromLogContext();

                if (isp.GetRequiredService <IInstrumentationSettings>().LogFilePerTest)
                {
                    loggerConfiguration.WriteTo
                    .File(logPath);
                }
                ;

                ILogger logger = loggerConfiguration.CreateLogger();

                return(logger);
            });

            services.AddScoped <ICommandExecutor>(isp =>
            {
                var remoteWebDriverSettings = isp.GetRequiredService <RemoteWebDriverSettings>();

                var commandExecutor = new HttpCommandExecutor(new Uri(remoteWebDriverSettings.RemoteUri), TimeSpan.FromSeconds(remoteWebDriverSettings.HttpCommandExecutorTimeoutInSeconds));

                return(commandExecutor);
            });

            services.AddScoped(isp =>
            {
                var factory                 = isp.GetRequiredService <IDriverSessionFactory>();
                var browserProperties       = isp.GetRequiredService <IBrowserProperties>();
                var remoteWebDriverSettings = isp.GetRequiredService <RemoteWebDriverSettings>();
                var environmentSettings     = isp.GetRequiredService <EnvironmentSettings>();
                var controlSettings         = isp.GetRequiredService <IControlSettings>();
                var deviceSettings          = isp.GetRequiredService <IDeviceProperties>();
                var logger              = isp.GetRequiredService <ILogger>();
                var testCaseReporter    = isp.GetRequiredService <ITestCaseReporter>();
                var httpCommandExecutor = isp.GetRequiredService <ICommandExecutor>();

                var driverSession = factory.Create(deviceSettings, browserProperties, remoteWebDriverSettings, environmentSettings, controlSettings, logger, testCaseReporter, httpCommandExecutor);
                return(driverSession);
            });

            beforeContainerBuild(prefix, services, testRunReporterContext);

            var reportingContextManager = new ReportingContextRegistrationManager(bootstrappingLogger, services, testRunReporterContext);

            reportingContextManager.AssertIsNotPartiallyConfigured();
            if (!reportingContextManager.IsConfigured)
            {
                reportingContextManager.PopulateDefaultReportingContexts();
            }

            _instance = services.BuildServiceProvider();
        }