Ejemplo n.º 1
0
 /// <summary>
 /// Scrolls directly to an element using JavaScript.
 /// </summary>
 /// <param name="actor">The screenplay actor.</param>
 /// <param name="driver">The WebDriver.</param>
 public override void PerformAs(IActor actor, IWebDriver driver)
 {
     if (Top != null)
     {
         actor.AsksFor(JavaScriptElementCall.To($"arguments[0].scrollTop = {Top};", Locator));
     }
     if (Left != null)
     {
         actor.AsksFor(JavaScriptElementCall.To($"arguments[0].scrollLeft = {Left};", Locator));
     }
 }
Ejemplo n.º 2
0
        /// <inheritdoc />
        protected override T ExecuteWhen(IActor actor)
        {
            var answer = actor.AsksFor(Question);

            VerifyAction(answer);
            return(answer);
        }
Ejemplo n.º 3
0
            protected override T Answer(IActor actor, IActionTags <TTag> ability)
            {
                var bestTag = ability.FindBestWhenTag(Question.Keys);
                var action  = Question[bestTag];

                return(actor.AsksFor(action));
            }
Ejemplo n.º 4
0
        /// <inheritdoc />
        protected override T Answer(IActor actor)
        {
            var converter = (IConverter <IWebElement, T>)_uIModelInfo.CreateConverter(actor);
            var question  = Element.Of(_containerTarget).WithCulture(_culture).As(converter);

            return(actor.AsksFor(question));
        }
Ejemplo n.º 5
0
        public void GivenTheseExistingCars(Table table)
        {
            table.Rows.ForEach(values =>
            {
                _actor.AttemptsTo(DeleteCar.ByRegistration(values["Registration"]));

                int customerId = _actor.AsksFor(
                    values.ContainsKey("Customer") ? StoredCustomerId.ForName(values["Customer"]) : StoredCustomerId.First());

                _actor.AttemptsTo(
                    InsertCar.WithRegistration(values["Registration"])
                    .ForCustomer(customerId)
                    .WithMake(values["Make"])
                    .WithModel(values["Model"]));
            });
        }
Ejemplo n.º 6
0
        /// <inheritsdoc />
        protected override async Task <TResult> Answer(IActor actor)
        {
            var result = await actor.AsksFor(Question);

            var projectedResult = await Selector(result);

            return(projectedResult);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// A simplified extension method for waiting.
        /// Calls will look like `Actor.WaitsUntil(...)` instead of `Actor.AsksFor(ValueAfterWaiting.Until(...))`.
        /// </summary>
        /// <typeparam name="TAnswer">The type of the question's answer value.</typeparam>
        /// <param name="actor">The Screenplay actor.</param>
        /// <param name="question">The question upon whose answer to wait.</param>
        /// <param name="condition">The expected condition for which to wait.</param>
        /// <param name="timeout">The timeout override in seconds. If null, use the standard timeout value.</param>
        /// <param name="additional">An additional amount to add to the timeout. Defaults to 0.</param>
        /// <returns></returns>
        public static TAnswer WaitsUntil <TAnswer>(
            this IActor actor,
            IQuestion <TAnswer> question,
            ICondition <TAnswer> condition,
            int?timeout    = null,
            int additional = 0) =>

        actor.AsksFor(ValueAfterWaiting.Until(question, condition).ForUpTo(timeout).ForAnAdditional(additional));
        public Model.ToDoItem Convert(IWebElement source, CultureInfo culture)
        {
            var target = Target.The("To do item").LocatedByWebElement(source);

            return(new Model.ToDoItem(
                       _actor.AsksFor(TextContent.Of(ToDoPage.ToDoItemName.RelativeTo(target)).Value),
                       target.ResolveFor(_webDriver).GetAttribute("class").Contains("completed")
                       ));
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Checks an element if not already selected
        /// Useful for checkboxes or radio buttons
        /// </summary>
        /// <param name="actor">The Screenplay Actor.</param>
        /// <param name="driver">The WebDriver.</param>
        public override void PerformAs(IActor actor, IWebDriver driver)
        {
            actor.WaitsUntil(Appearance.Of(Locator), IsEqualTo.True());
            bool selectedState = actor.AsksFor(SelectedState.Of(Locator));

            if (selectedState != CheckState)
            {
                actor.AttemptsTo(Click.On(Locator));
            }
        }
Ejemplo n.º 10
0
        public void GivenThisExistingCustomer(Table table)
        {
            var values = table.Rows.Single();

            _actor.AttemptsTo(DeleteCustomers.WithName(values["Name"]));

            _actor.AttemptsTo(
                InsertCustomer.Named(values["Name"])
                .Titled(values.GetStringOrDefault("Title"))
                .OfAddress(
                    values.GetStringOrDefault("Address Line 1"),
                    values.GetStringOrDefault("Address Line 2"),
                    values.GetStringOrDefault("Address Line 3"),
                    values.GetStringOrDefault("Postcode"))
                .WithHomePhone(values.GetStringOrDefault("Home Phone"))
                .WithMobile(values.GetStringOrDefault("Mobile"))
                .WithAccountInvoicingSetTo(values.GetBoolOrDefault("Account Invoicing")));

            _storedCustomer = _actor.AsksFor(StoredCustomer.WithName(values["Name"]));
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Execute the action
        /// </summary>
        /// <param name="actor"></param>
        /// <param name="ability"></param>
        protected override void ExecuteWhen(IActor actor, WebBrowser ability)
        {
            var wait = new WebDriverWait(ability.Driver, _timeout);

            try
            {
                wait.Until(_ => _isAnswered(actor.AsksFor(_question)));
            }
            catch (WebDriverTimeoutException ex)
            {
                throw new TimeoutException($"The question '{_question}' was not answered after waiting {_timeout.ToString()}", ex);
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Gets an answer from the cache.
        /// If the cache does not have the answer, it asks the Question using the given Actor.
        /// Uses the lock to be thread-safe.
        /// </summary>
        /// <typeparam name="TAnswer">The answer type.</typeparam>
        /// <param name="question">The Question.</param>
        /// <param name="actor">The Screenplay Actor.</param>
        /// <returns></returns>
        public TAnswer Get <TAnswer>(ICacheableQuestion <TAnswer> question, IActor actor)
        {
            lock (Lock)
            {
                if (!Cache.ContainsKey(question))
                {
                    TAnswer answer = actor.AsksFor(question);
                    Cache.Add(question, answer);
                }

                return((TAnswer)Cache[question]);
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Waits until the question's answer value meets the condition.
        /// If the expected condition is not met within the time limit, then an exception is thrown.
        /// Returns the actual awaited value.
        /// </summary>
        /// <param name="actor">The actor.</param>
        /// <returns></returns>
        protected TValue WaitForValue(IActor actor)
        {
            // Set variables
            TValue actual    = default(TValue);
            bool   satisfied = false;

            ActualTimeout = CalculateTimeout(actor);

            // Adjust log level if necessary (to avoid too many messages)
            LogSeverity original = actor.Logger.LowestSeverity;

            if (SuppressLogs && actor.Logger.LowestSeverity < LogSeverity.Warning)
            {
                actor.Logger.LowestSeverity = LogSeverity.Warning;
            }

            // Start the timer
            Stopwatch timer = new Stopwatch();

            timer.Start();

            try
            {
                // Repeatedly check if the condition is satisfied until the timeout is reached
                do
                {
                    actual    = actor.AsksFor(Question);
                    satisfied = Condition.Evaluate(actual);
                }while (!satisfied && timer.Elapsed.TotalSeconds < ActualTimeout);
            }
            finally
            {
                // Return the log level to normal, no matter what goes wrong
                if (SuppressLogs)
                {
                    actor.Logger.LowestSeverity = original;
                }

                // Stop the timer
                timer.Stop();
            }

            // Verify successful waiting
            if (!satisfied)
            {
                throw new WaitingException <TValue>(this, actual);
            }

            // Return the actual awaited value
            return(actual);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Navigates the browser to the target URL if necessary.
        /// </summary>
        /// <param name="actor">The screenplay actor.</param>
        public void PerformAs(IActor actor)
        {
            string currentUrl = actor.AsksFor(CurrentUrl.FromBrowser());

            if (Acceptable.Match(currentUrl).Success)
            {
                actor.Logger.Info("The current URL is acceptable, so navigation will not be attempted");
            }
            else
            {
                actor.Logger.Info("The current URL is not acceptable, so navigation will be attempted");
                actor.AttemptsTo(Navigate.ToUrl(Url));

                if (AcceptAlerts)
                {
                    actor.AttemptsTo(AcceptAlert.IfItExists());
                }
            }
        }
        /// <inheritdoc />
        public TResult ExecuteTakeScreenshot <TResult, TAbility>(TAbility actionAbility,
                                                                 IActor actor,
                                                                 Func <TResult> execute,
                                                                 Func <string> nextScreenshotName,
                                                                 IObserver <ScreenshotInfo> screenshotObserver)
        {
            bool canTakeScreenshot = true;

            if (!(actionAbility is WebBrowser webBrowser))
            {
                webBrowser        = actor.AsksFor(Tranquire.Questions.Create(TakeScreenshotOnErrorStrategy.GetWebBrowserQuestionName, (IActor a, WebBrowser w) => w));
                canTakeScreenshot = false;
            }

            try
            {
                if (canTakeScreenshot)
                {
                    _count++;
                }
                var result = execute();
                if (canTakeScreenshot && _count == _sampleSize)
                {
                    TakeScreenshot();
                }
                return(result);
            }
            catch (Exception)
            {
                TakeScreenshot();
                throw;
            }

            void TakeScreenshot()
            {
                var name       = nextScreenshotName();
                var screenshot = ((ITakesScreenshot)webBrowser.Driver).GetScreenshot();

                screenshotObserver.OnNext(new ScreenshotInfo(screenshot, name));
                _count = 0;
            }
        }
Ejemplo n.º 16
0
        public void GivenTheFollowingExistingCar(Table table)
        {
            var values = table.Rows.Single();

            _actor.AttemptsTo(DeleteCar.WithRegistration(values["Registration"]));

            int customerId = _actor.AsksFor(StoredCustomerId.ForName(values["Customer"]));

            _actor.AttemptsTo(
                InsertCar.WithRegistration(values["Registration"])
                .ForCustomer(customerId)
                .WithMake(values.GetStringOrDefault("Make"))
                .WithModel(values.GetStringOrDefault("Model"))
                .MotExpiringOn(values.GetDateOrDefault("MOT Expiry"))
                .SuppressingMotReminder(values.GetBoolOrDefault("Suppress MOT Reminder")));

            _storedCar = _actor.AsksFor(StoredCar.WithRegistration(values["Registration"]));
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Gets the desired cookie from the WebDriver as a System.Net.Cookie.
        /// Internally calls BrowserCookie and converts the internal OpenQA.Selenium.Cookie.
        /// Optionally reset the cookie's expiration.
        /// Warning: The cookie's expiration will be wrong.
        /// </summary>
        /// <param name="actor">The actor.</param>
        /// <returns></returns>
        public System.Net.Cookie RequestAs(IActor actor)
        {
            // Get the cookie from WebDriver
            var seCookie  = actor.AsksFor(BrowserCookie.Named(CookieName));
            var netCookie = new System.Net.Cookie(seCookie.Name, seCookie.Value, seCookie.Path, seCookie.Domain);

            // Reset the expiration if applicable
            if (Expiration != null)
            {
                netCookie.Expires = (DateTime)Expiration;
            }

            // IE gives cookies a double-slash path, which breaks RestSharp
            if (netCookie.Path == "//")
            {
                netCookie.Path = "/";
            }

            // Return the System.Net.Cookie
            return(netCookie);
        }
Ejemplo n.º 18
0
        public void ThenTheJobShouldBeAddedToTheSystemWithTheDetailsProvided()
        {
            _uiViewInfo.Should().NotBeNull();

            JobInfo matchingJob = null;

            Poller.PollForSuccess(() =>
            {
                JobInfo[] storedJobs = _actor.AsksFor(StoredJobs.ForRegistration(_uiViewInfo.Registration));

                matchingJob = storedJobs.SingleOrDefault(j =>
                                                         j.Registration == _uiViewInfo.Registration &&
                                                         j.Description == _uiViewInfo.Description &&
                                                         j.Date == _uiViewInfo.Date &&
                                                         j.Hours == _uiViewInfo.Hours &&
                                                         j.Mileage == _uiViewInfo.Mileage);

                return(matchingJob != null);
            });

            matchingJob.Should().NotBeNull();
        }
        /// <inheritdoc />
        public TResult ExecuteTakeScreenshot <TResult, TAbility>(TAbility actionAbility,
                                                                 IActor actor,
                                                                 Func <TResult> execute,
                                                                 Func <string> nextScreenshotName,
                                                                 IObserver <ScreenshotInfo> screenshotObserver)
        {
            if (!(actionAbility is WebBrowser webBrowser))
            {
                webBrowser = actor.AsksFor(Tranquire.Questions.Create(GetWebBrowserQuestionName, (IActor a, WebBrowser w) => w));
            }

            try
            {
                return(execute());
            }
            catch (Exception)
            {
                var name       = nextScreenshotName();
                var screenshot = ((ITakesScreenshot)webBrowser.Driver).GetScreenshot();
                screenshotObserver.OnNext(new ScreenshotInfo(screenshot, name));
                throw;
            }
        }
Ejemplo n.º 20
0
 /// <summary>
 /// Gets a web element's JavaScript textContent value.
 /// </summary>
 /// <param name="actor">The actor.</param>
 /// <param name="driver">The WebDriver.</param>
 /// <returns></returns>
 public override string RequestAs(IActor actor, IWebDriver driver) =>
 actor.AsksFor(JavaScriptElementCall.To("return arguments[0].textContent;", Locator)).ToString();
Ejemplo n.º 21
0
        public void ThenIShouldSeeTheSuccessMessage(string expectedMessage)
        {
            string successMessage = _actor.AsksFor(Text.Of(ChangeCarRegistrationPage.SuccessMessage));

            successMessage.Should().Be(expectedMessage);
        }
Ejemplo n.º 22
0
 /// <summary>
 /// Clicks the web element.
 /// Use browser actions instead of direct click (due to IE).
 /// </summary>
 /// <param name="actor">The screenplay actor.</param>
 /// <param name="driver">The WebDriver.</param>
 public override void PerformAs(IActor actor, IWebDriver driver) =>
 actor.AsksFor(JavaScriptElementCall.To("arguments[0].click();", Locator));
Ejemplo n.º 23
0
 /// <inheritsdoc />
 protected override TResult Answer(IActor actor)
 {
     return(Selector(actor.AsksFor(Question)));
 }
Ejemplo n.º 24
0
        /// <summary>
        /// Gets the latest window handle and switches to it.
        /// </summary>
        /// <param name="actor">The Screenplay actor.</param>
        public void PerformAs(IActor actor)
        {
            string handle = actor.AsksFor(WindowHandle.Latest());

            actor.AttemptsTo(SwitchWindow.To(handle));
        }
Ejemplo n.º 25
0
 /// <summary>
 /// Evalutes the Condition against the Question's answer.
 /// </summary>
 /// <param name="actor">The Screenplay Actor.</param>
 /// <returns></returns>
 public bool Evaluate(IActor actor)
 {
     _answer = actor.AsksFor(Question);
     return(Condition.Evaluate(_answer));
 }
Ejemplo n.º 26
0
 protected override ImmutableArray <Model.ToDoItem> Answer(IActor actor, WebBrowser ability)
 {
     return(actor.AsksFor(Element.Of(ToDoPage.ToDoItem).Many().As(new WebElementToToDoItemConverter(actor, ability.Driver))));
 }
Ejemplo n.º 27
0
        /// <summary>
        /// Gets the latest window handle and switches to it.
        /// </summary>
        /// <param name="actor">The Screenplay Actor.</param>
        /// <param name="driver">The WebDriver from the BrowseTheWeb Ability.</param>
        public override void PerformAs(IActor actor, IWebDriver driver)
        {
            string handle = actor.AsksFor(WindowHandle.Latest());

            actor.AttemptsTo(SwitchWindow.To(handle));
        }
Ejemplo n.º 28
0
 /// <summary>
 /// A simplified extension method for caching answers.
 /// Calls will look like `Actor.GetsCached(...)` instead of `Actor.AsksFor(CachedAnswer.For(...))`.
 /// WARNING: Do NOT cache answers to every Question.
 /// Only cache answers that you know will be fairly constant.
 /// Use this extension method only when explicitly caching answers.
 /// </summary>
 /// <typeparam name="TAnswer">The answer type.</typeparam>
 /// <param name="actor">The Actor.</param>
 /// <param name="question">The Question.</param>
 /// <returns></returns>
 public static TAnswer GetsCached <TAnswer>(this IActor actor, ICacheableQuestion <TAnswer> question) =>
 actor.AsksFor(CachedAnswer <TAnswer> .For(question));
        public void WhenIViewTheCustomer()
        {
            _storedCustomer.Should().NotBeNull();

            int customerId = _actor.AsksFor(StoredCustomerId.ForName(_storedCustomer.Name));

            _actor.AttemptsTo(ViewCustomer.WithId(customerId));
        }
Ejemplo n.º 30
0
 public int AnsweredBy(IActor actor)
 {
     return(actor.AsksFor(TextContent.Of(ToDoPage.ToDoItemsLeftCounter).AsInteger()));
 }