zoukankan      html  css  js  c++  java
  • WatiN, Ajax and some Extension Methods(整理)

    Whilst I've been working with WatiN over the past couple of months Ihave encountered a few issues especially that unfortunately WatiN wasunable to solve straight out of the box, so I thought I would knock apost together that contains the extension methods I have managed tocobble together from various sources on the Internet and a little bitfrom my own head.

    WaitUntilEnabled

    I encountered this issue whilst working with the CascadingDropDown provided by theAjax Control Toolkit,now WatiN does provide a function called WaitUntil which allows you topass in the name of the attribute you want to examine and the valuethat you expect the attribute to become, unfortunately however, itseems the CascadingDropDown adds a "disabled" attribute with a value of"true" to the html page. The drop down list then becomes enabled whenthe disabled attribute no longer exists or is set to false. Thereforeit was necessary to write an extension method that waited until thecontrol no longer had a "disabled" property with a value of "true. Themethod is as follows:

    /// <summary>
    ///
    Waits until the specified element is enabled within the web page.
    /// </summary>
    /// <param name="element">
    The element.</param>
    public static T WaitUntilEnabled<T>(this IElement element)where T :class
    {
      var timer =newSimpleTimer(IE.Settings.WaitForCompleteTimeOut);

      do
      {
        varvalue = element.GetAttributeValue("disabled");

        if(value !="True"&&value !="true")
        {
            return element as T;
        }
        Thread.Sleep(200);
      }
      while(!timer.Elapsed);

      throw newTimeoutException("Waited too long for "+ element.Id +" to become enabled");
    }

    UPDATED15/09/08: Whilst preparing for my Ready, Steady, Speak session at RemixI came across a small bug where the value retrieved for the disabledattribute was "True" instead of "true" as initially thought, I don'tknow what caused the difference to occur but I have added theadditional check anyway.

    The usage of this method is as follows:

    ie.SelectList(Find.ById("MyCascadingDropDown")).WaitUntilEnabled().Select("AValue");

    IfExists

    This is just an extension method I wrote to make it a little easier to work with elements that don't exist:

    /// <summary>
    ///
    Checks whether the element exists, if so performs the specified action,
    ///otherwise just returns the current element object.
    /// </summary>
    /// <typeparam name="T">
    The type of element to check for existence.</typeparam>
    /// <param name="element">
    The element.</param>
    /// <param name="action">
    The action.</param>
    /// <returns></returns>
    public static T IfExists<T>(thisElementelement,Action<T> action)where T :class
    {
      if(element.Exists)
      {
          action(element as T);
      }

      return element as T;
    }

    This method can be used as follows:

    ie.TextField(Find.ById("MyTextField")).IfExists<TextField>(e => e.TypeText("AValue"));
      

    WaitForAsyncPostBackToComplete

    Ifyou are working with controls within an update panel you willinevitably come across a situation where a value is changed via anasync postback and whilst that postback is taking place WatiN will tryand perform. another action which results in an error.The solution tothis problem was found after searching the Internet for a little whileand I came across thispostwhich explains the problem in a little more detail.

    Ihave modified the original method slightly to make it an extension forthe IE browser object, it is used to determine whether the current pageis within an asynchronous postback,unfortunately in order touse this method the page you are testing needs to have a JavaScript.method defined so if you don't have control over the website you couldbe a little stuck, here is the Javascript.


    <script.type="text/javascript">
    var
    prm = Sys.WebForms.PageRequestManager.getInstance();
    functionIsPageInAsyncPostback()
    {
      returnprm.get_isInAsyncPostBack();
    }
    </script>

    The C# method implementation is as follows:

    /// <summary>
    ///
    Waits for async post back to complete.
    /// </summary>
    /// <param name="ie">
    The ie instance to use.
    </param>
    public static voidWaitForAsyncPostBackToComplete(this IE ie)
    {
    bool isInPostback =true;
    while(isInPostback)
    {
      isInPostback =Convert.ToBoolean(ie.Eval("IsPageInAsyncPostback();"));
      if(isInPostback)
      {
        Thread.Sleep(200);
    //sleep for 200ms and query again
      }
    }
    }

    Aftera kind comment from Jo (see below), I have modified this as there is noneed to place the IsPageInAsyncPostback method inside of the page, Ijust needed to modify the Eval method to make the entire call, asfollows:

    /// <summary>
    ///
    Waits for async post back to complete.
    /// </summary>
    /// <param name="ie">
    The ie instance to use.</param>
    public static voidWaitForAsyncPostBackToComplete(this IBrowser ie)
    {
      switch(ie.BrowserType)
      {
          caseBrowserType.InternetExplorer:
        {
            boolisInPostback =true;
            while(isInPostback)
          {
              isInPostback =Convert.ToBoolean(ie.Eval("Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack();"));
              if(isInPostback)
            {
                  Thread.Sleep(200);//sleep for 200ms and query again
            }
          }
            break;
        }
      }
    }

    And can be used like this:

    SelectListlist = ie.SelectList(Find.ById("MySelectList"));
    list.Option("TestOption").Select();

    ie.WaitForAsyncPostBackToComplete();

    SelectListchildList = ie.SelectList(Find.ById("MyChildSelectList"));
    list.Option("TestChildOption").Select();

    ByPartialId

    Thefinal useful method is ByPartialId, this is merely a wrapper around aregular expression but it does save quite a bit of typing and needingto remember the regular expression syntax. I found this onAyende Rahien's blog:

    /// <summary>
    ///
    Gets an attribute constraint using a partial id.
    /// </summary>
    /// <param name="partialElementId">
    The partial element id.</param>
    /// <returns></returns>
    public staticAttributeConstraintByPartialId(stringpartialElementId)
    {
    returnFind.ById(newRegex(".*"+ partialElementId +"$"));
    }


    from:
    http://www.51testing.com/?uid-272264-action-viewspace-itemid-134277
  • 相关阅读:
    mysql5.7.11修改root默认密码
    linux tar文件解压
    用Maven插件生成Mybatis代码/数据库
    java对象与json对象间的相互转换
    json串转对象
    maven web 项目中启动报错java.lang.ClassNotFoundException: org.springframework.web.util.Log4jConfigListener
    MyBatis多数据源配置(读写分离)
    使用HTML5 Web存储的localStorage和sessionStorage方式
    谷歌浏览器 DEV Tools
    数据库建表原则
  • 原文地址:https://www.cnblogs.com/CodingPerfectWorld/p/1895599.html
Copyright © 2011-2022 走看看