2012-07-10 69 views
7

目前我正在尝试使用Selenium和Proboscis编写一个自动化测试套件。我试图抽象webdriver并通过工厂模式实现。 Page_object类也在这里创建,它在创建对象时将webdriver作为参数。以下是代码。Selenium webdriver的工厂模式

 import selenium.webdriver as webdriver 
    from proboscis import TestProgram 
    from proboscis import test 
    from proboscis import before_class 
    from proboscis import after_class  

    class WebdriverFactory: 
     @staticmethod 
     def getWebdriver(browserName): 
      if(browserName == 'firefox'): 
      return webdriver.Firefox() 
      elif(browserName == 'chrome'): 
      return webdriver.Chrome() 
      elif(browserName == 'ie'): 
      return webdriver.Ie()   

      raise Exception("No such " + browserName + " browser exists") 

    class Page_Object: 
    def __init__(self, driver): 
     self.driver = driver 

    def go_to_home(self): 
     self.driver.get("http://google.com") 
     return self 
    def go_to_page(self,url): 
     self.driver.get(url) 
     return self 
    def run_search(self, url, query): 
     self.driver.get(url) 
     self.driver.find_element_by_id(locators['search_box']).send_keys(query) 
     self.driver.find_element_by_id(locators['search_button']).click() 

    def tear_down(self): 
     self.driver.close() 

    @test(groups=['selenium']) 
    class Test_Scripts: 

    @test(groups=['WebDemo']) 
    def test_1(self): 
     driver = WebdriverFactory.getWebdriver("firefox") 
     pageObj = Page_Object(driver) 
     pageObj.run_search("http://google.com",'apples') 
     pageObj.tear_down()  
    def run_tests(self): 
     TestProgram().run_and_exit() 

    Test_Scripts().run_tests() 

这是做这件事的正确方法吗?或者有更好的解决方案吗? 如果你发现一些愚蠢的话,请指出并忽略我的疏忽,因为我是Python和Selenium的新手。

+1

真的很惊讶,这个问题没有得到太多的关注:( – 2012-08-24 20:10:38

回答

2

您正在正确实施页面对象,因为您按大多数人的方式执行该操作。

我已经做了页面对象有点不同 - 不需要webdriver来实例化它们。因为我经常碰到几个不同主体内容的页面,但是页眉和页脚部分是相同的。因此,不是在每个页面对象中重复页眉/页脚定位器和方法,而是为页眉提供单独的页面obj,而仅用于页脚。但随后使用1个webdriver实例化多个页面对象来测试单个页面,似乎违反了范例。所以我的页面对象实际上只是一个定位器和方法的集合,并不一定是一个webdriver。

我意识到你没有提到页眉或页脚......我猜为什么大多数人围绕webdriver构建他们的页面对象的原因是创建一个范例,每个页面只假设一个页面对象。在我的情况下,这会导致跨页对象的代码重复。需要考虑的事情。希望有所帮助!

+1

帕特米克,你有一些例子来分享我正在寻找吗?顺便说一句,目前使用[this](https:// github。 com/ncbi/robotframework-pageobjects)作为起点,并结合'机器人框架'。正如你所提到的,有一些共同的对象,不想在每一页上重复。也没有太多的手来获取'inheretence'来获取它加工。 – Rao 2016-02-10 04:57:32