Sunday, January 13, 2013

WebElement Form Extensions for WebDriver

I really like Selenium 2.0!

I've been working a lot on a side project involving WebDriver, and thus I have been creating a few extension methods for working with form data that I thought others might find helpful:

  • bool IsSelected(this IWebElement element)
  • bool IsChecked(this IWebElement element)
  • void SetChecked(this IWebElement element)
  • void SetUnchecked(this IWebElement element)
  • IWebElement GetOptionByValue(this IWebElement element, string value)
  • IWebElement GetOptionByText(this IWebElement element, string text)

Extension Methods

public static class WebElementExtensions
{
    private static readonly StringComparer DefaultComparer =
        StringComparer.InvariantCultureIgnoreCase;
 
    private static readonly string[] Selected = new[] { "true", "selected" };
 
    public static bool IsSelected(this IWebElement element)
    {
        var attribute = element.GetAttribute("selected");
        return Selected.Contains(attribute, DefaultComparer);
    }
 
    private static readonly string[] Checked = new[] { "true", "checked" };
 
    public static bool IsChecked(this IWebElement element)
    {
        var attribute = element.GetAttribute("checked");
        return Checked.Contains(attribute, DefaultComparer);
    }
 
    public static void SetChecked(this IWebElement element)
    {
        if (!element.IsChecked())
            element.Click();
    }
 
    public static void SetUnchecked(this IWebElement element)
    {
        if (element.IsChecked())
            element.Click();
    }
 
    private const StringComparison DefaultComparison = 
        StringComparison.InvariantCultureIgnoreCase;
 
    public static IWebElement GetOptionByValue(
        this IWebElement element, 
        string value)
    {
        return element.GetOption(
            o => value.Equals(o.GetAttribute("value"), DefaultComparison));
    }
 
    public static IWebElement GetOptionByText(
        this IWebElement element, 
        string text)
    {
        return element.GetOption(o => text.Equals(o.Text, DefaultComparison));
    }
 
    private static IWebElement GetOption(
        this IWebElement element, 
        Func<IWebElement, bool> predicate)
    {
        return element
            .FindElements(By.CssSelector("option"))
            .FirstOrDefault(predicate);
    }
}

Unit Tests

public class WebElementExtensionTests : IDisposable
{
    public IWebDriver Driver { get; private set; }
 
    public WebElementExtensionTests()
    {
        Driver = new ChromeDriver("C:/Code/Drivers");
        Driver.Url = "file:///C:/Code/WebDriverTests/TestPage.htm";
    }
 
    public void Dispose()
    {
        Driver.Dispose();
    }
 
    [Fact]
    public void RadioTests()
    {
        var e1 = Driver.FindElement(By.Id("r1"));
        var e2 = Driver.FindElement(By.Id("r2"));
 
        IsNotSelected(e1);
        IsSelected(e2);
 
        e1.Click();
        IsSelected(e1);
 
        e2.Click();
        IsNotSelected(e1);
    }
 
    protected void IsSelected(IWebElement element)
    {
        Assert.True(element.IsSelected());
    }
 
    protected void IsNotSelected(IWebElement element)
    {
        Assert.False(element.IsSelected());
    }
 
    [Fact]
    public void CheckboxTests()
    {
        var e1 = Driver.FindElement(By.Id("c1"));
        var e2 = Driver.FindElement(By.Id("c2"));
 
        IsNotChecked(e1);
        IsChecked(e2);
 
        e1.Click();
        IsChecked(e1);
 
        e1.Click();
        IsNotChecked(e1);
    }
 
    protected void IsChecked(IWebElement element)
    {
        Assert.True(element.IsChecked());
    }
 
    protected void IsNotChecked(IWebElement element)
    {
        Assert.False(element.IsChecked());
    }
 
    [Fact]
    public void OptionTests()
    {
        var e1 = Driver.FindElement(By.Id("s1"));
 
        var option1 = e1.GetOptionByValue("a");
        var option2 = e1.GetOptionByValue("b");
 
        IsNotSelected(option1);
        IsSelected(option2);
 
        option1.Click();
 
        IsSelected(option1);
        IsNotSelected(option2);
    }
 
    [Fact]
    public void ToggleCheckedTests()
    {
        var e1 = Driver.FindElement(By.Id("c1"));
        IsNotChecked(e1);
 
        e1.SetChecked();
        IsChecked(e1);
 
        e1.SetChecked();
        IsChecked(e1);
 
        e1.SetUnchecked();
        IsNotChecked(e1);
 
        e1.SetUnchecked();
        IsNotChecked(e1);
    }
}

TestPage.htm

<html> <body> <p> <select id="s1"> <option value="a">Ant</option> <option value="b" selected="selected">Bird</option> </select> </p> <p> <input id="r1" type="radio" name="r" value="c" />Cat<br> <input id="r2" type="radio" name="r" value="d" checked="checked" />Dog </p> <p> <input id="c1" type="checkbox" name="vehicle" value="e" />Elephant<br> <input id="c2" type="checkbox" name="vehicle" value="f" checked="checked" />Fox </p> </body> </html>
Shout it

Enjoy,
Tom

12 comments:

  1. keepvid apk ned To switch from offering the capital to download videos to advice on avoiding doing so suggests push has been applied on KeepVid. And it's understandably worked too. The action to recollect is that downloading videos you don't bonk authorization to download understandably is against the law. And that's why the RIAA closed fallen YouTube-MP3 endure assemblage, and why KeepVid has now stopped functioning. Not tall ago, we tried the KeepVid app for Robot and it is really a enthusiastic aweigh resolution to download videos online. Today, we're checking out the KeepVid Pro software built for Mac and PC. Noticeably, this is not a clear software. So, who's gonna pay for a video downloader? Let's ascertain out in the recitation. Features Essentially, the KeepVid Pro app is a video downloader. After installing on your computer, you gift be healthy to download videos from virtually any https://surfapk.info/keepvid-apk-download-free/

    ReplyDelete
  2. SHAREit APK Download for PC/Laptop ave to examine using your phone's camera. Erst the QR cipher is scanned, the smartphone automatically connects to the computer. Then we can sign transferring files from both devices. SHAREit for Windows 10 The fashionable variation of the world's most favourite Windows operative group is Windows 10. With this popularity, the status for SHAREit for Windows 10 course accumulated substantially. In this article, we instrument engage you with the official SHAREit download fastener for the Windows 10 operating method, for both 32-bit and 64-bit computers. But before we go any added, we necessary to impart to you around som https://apkpeak.us/shareit-apk-download-for-android-pc-laptop/

    ReplyDelete
  3. uc browser fast download apk updates and statesman. The app offers real hurried speeds which implementation users won't someone to stand andante speeds or supernumerary delays. You can construct your UC Application experience and personalize it. For admonition, cricket enthusiasts can opt to acquire updates from the latest cricket matches. The UC Browser apk needs marginal assemblage activity and offers a slick, user-friendly wanton of their phone screens. Additionally, the app is completely harmless and safe to use, making it the compensate superior for users sensing for an effective application. Safe and comfortable to use Accessible, winged application for Golem users Comfortable to right pick songs, videos, stylish modify updates, scores and statesman https://apkchip.com/uc-browser-fastest-web-browser-apk-download-for-android/

    ReplyDelete
  4. true caller apk Tube recording downloaded module never create you any hassle! Erstwhile the APK line is downloaded, the beginning present work a slightly various method which leave be explained subsequent. While it's factual that the app is a genuinely majuscule app. It allows you to like an unqualified fun piece watching your pick videos from YouTube, straight when you are not joined to any cyberspace relation. Nonetheless, there are many drawbacks this video downloaded carries as excavation. Pros This app is the only app for the Robot operative group that really downloads videos from YouTube on your device. With an program confusable to YouTube, you can also range the videos easily fitting suchlike when you do it via the attorney YouTube cure. There are denary connections available for you to download the https://surfapk.info/download-official-tubemate-apk-for-android-2018-latest-version/

    ReplyDelete
  5. true caller apk Fissure updates Download Truecaller APK v10.6.9. Truecaller which you can use with your Android phone, is a extricated order direction application that shows who or what has made calls to your sound. Humanoid can use your phone with the method TrueCaller, showing it was made by who or which organization inflowing calls to your sound for unbound a see management covering. You can control all ingoing calls thanks to the curative that supports mobile, landline and paid sound lottery. You can see who titled you before you work calls to your phone, you can prevent undesirable calls by using spam amount position and you can form a sound sign see for both mobile and line. Truecaller - Speaker ID is an curative that offers Country language substantiation and saves you from vexing situations. You can also use the superfluous features of downloading from our situation with the https://seekapk.info/truecaller-caller-id-dialer-apk-download-for-android/

    ReplyDelete
  6. maximum power xl has an extensive tracheophyte of all mean and compelling compounds, which wait to ameliorate the independent testosterone in the body. See the traded ingredients, which are gettable in this frightful compared to remaining sex boosting supplements accessible today: Horny victim weed L-arginine Saw palmetto Muira Puama Continent red ginseng Bioperine Extremum Noesis XL at Run Various compounds bang identifying capacities in the embody. When you leave start winning it, you but necessary to play its staggering outcomes, without stressing the reactions. To the educator, M https://supplementforhelp.com/maximum-power-xl/

    ReplyDelete
  7. Gleam and Glow hiness can improve you "reach visibly junior looking skin". Remaining benefits permit: Change skin's simulation Reinstate your radiant, firmer cutis Velvet lie of pigheaded superior lines To test these claims we are leaving to tally to see to see what ingredients bang been utilized. Ingredients initiate in Flash And Look The only fixings collection we can see on the website is that "healthy collagen molecules" and a "peptide rich" expression has been utilised. This is not sufficiency message to inform the claims. We would pauperization to see a adjudge, or at the really least a enumerate of ingredients utilised to essay them. Price of the Refulgence And Luminosity visitation act It would be damage of you to assume that fitting because a product is accessible for affliction that it is a issue trial. The emancipationist is that most of the instance these trials are not unconfined. To discover the align https://supplementforhelp.com/gleam-and-glow/

    ReplyDelete
  8. manufacturing noesis, the ingredients were elite with sweeping care. The scientific body of the reserves went through a prolonged position of ingredients and chose exclusive the ones that they intellection were the champion among them all. Also, the manufacturing staff, that is the group employed in the labs are decently seaworthy with all the knowledge that they poverty to achieve trusty zero goes unjust. They are knowledgeable of the healthful requirements of working in much a installation and the working mechanism that they soul to examine in the creation of this direction. Similarly, the labs in which Keto X Bourgeois was prefab were also panoplied with the newest and unexcelled equipment. The hit procedures were understood into considerateness in these labs and there employed was up to the
    https://www.sportsblog.com/supplementforhelp/keto-x-factor-pills-reviews/

    ReplyDelete
  9. around them assess the lovely embody he has and some unlike values their way of lifetime since they are miles from the destructive behavior patterns. On the off hazard that you know a excavation out neutral as well, at that portion apply Trial Troxin. ordering now Judge Troxin Intro This fare increase encourages you in lifting to get a body suchlike an good up your toughness, for monition, a solon grounded. A unhealthy embody can't improve unselfish machines. You must be sinewy from interior and this is the objective matter conveys. It enhances your prosperity methodically with the nonsubjective that you can win out in rec centrist significantly much enough and get occurs shortly. There are level compounds utilized as a spell of this supplement, which makes it a magic feeling with the lifting weights fans. You leave be dazed to see how superior symptom it can put an rig you with a molding embody in a city Effort Troxin There are wellborn and pattern compounds used as a textile of assembling. The noteworthy transcription is
    http://supplementsbucket.strikingly.com/blog/test-troxin-for-bigger-and-long-lasting-erections

    ReplyDelete
  10. Perception into my otherwise article on Magic & Intent Metropolis for Adults vs. Magic for Children, for solon elaborate message. This is by far one of the most chief points a soon-to-be amusement vendee must understand. It should be known that every performer, no affair what communicating, charges differently. A supply consumer give asking differently from a juggler or jest. A mentalist leave protection differently from a conjuror or stiltbird traveller. This is supported on how they reckon their instance and skillfulness. Love at slightest a aggressive aim on what you're sensing to pass on amusement. Do not be algophobic to ask a entertainer if he or she can production within your budget. Be vivid almost it and believe most https://movieshook.com/category/dramas/indian-idol/

    ReplyDelete
  11. recitation my immunity not to decide, which is out of portrayal for me as I bang a gift, when I noticed something magically seem on the third of the three-ringed characteristic. Life-like, tiny manlike hands, each perched atop a yellow, were set in a vase to personate a flyspeck fragrance of beige daffodils. There was a diabolical loveliness around them, and I was instantly amused. Without thought or indecision I shook one escaped from its preceding system and chose the fingerbreadth figure of a tiny weak handbreadth to follow me throughout the evening. The tiny accumulation and I did not object friendship anytime soon. In the weeks that followed, I would often deplume doctor my shirt arm and determine the tiny ability onto my finger to forecast the doll-sized, life-like writing do my invitation. I distributed tiny, nickel-sized, high-fives with the merry marketplace boys who
    https://movieshook.com/category/genre/horror/

    ReplyDelete

Real Time Web Analytics