/// <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)); } }
/// <inheritdoc /> protected override T ExecuteWhen(IActor actor) { var answer = actor.AsksFor(Question); VerifyAction(answer); return(answer); }
protected override T Answer(IActor actor, IActionTags <TTag> ability) { var bestTag = ability.FindBestWhenTag(Question.Keys); var action = Question[bestTag]; return(actor.AsksFor(action)); }
/// <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)); }
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"])); }); }
/// <inheritsdoc /> protected override async Task <TResult> Answer(IActor actor) { var result = await actor.AsksFor(Question); var projectedResult = await Selector(result); return(projectedResult); }
/// <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") )); }
/// <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)); } }
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"])); }
/// <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); } }
/// <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]); } }
/// <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); }
/// <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; } }
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"])); }
/// <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); }
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; } }
/// <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();
public void ThenIShouldSeeTheSuccessMessage(string expectedMessage) { string successMessage = _actor.AsksFor(Text.Of(ChangeCarRegistrationPage.SuccessMessage)); successMessage.Should().Be(expectedMessage); }
/// <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));
/// <inheritsdoc /> protected override TResult Answer(IActor actor) { return(Selector(actor.AsksFor(Question))); }
/// <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)); }
/// <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)); }
protected override ImmutableArray <Model.ToDoItem> Answer(IActor actor, WebBrowser ability) { return(actor.AsksFor(Element.Of(ToDoPage.ToDoItem).Many().As(new WebElementToToDoItemConverter(actor, ability.Driver)))); }
/// <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)); }
/// <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)); }
public int AnsweredBy(IActor actor) { return(actor.AsksFor(TextContent.Of(ToDoPage.ToDoItemsLeftCounter).AsInteger())); }