我最近切换到一个新项目,我们所有的selenium测试都是用Python编写的。我想知道我是否可以通过使用装饰器来减少代码量
我们现在得到的是:
class BasePage(object):
view_button = ".//a[text()='View']"
create_button = ".//a[text()='Create']"
#some code here
class BaseTestCase(unittest.TestCase):
setUpclass(cls):
#code here
def find(cls,xpath):
return cls.driver.find_element_by_xpath(xpath)
class SomeTest(BaseTestCase):
def test_00_something(self):
self.find(self.view_button).click()
我在想是否有办法将整个self.find(self.view_button).click()
最小化为click.view_button
我听说可以使用装饰器完成,但作为一个Java人我没有成功。
答案 0 :(得分:2)
您还可以查看以下解决方案;创建新模块 - navigation.py with:
class Button():
def __init__(self,driver, locator):
self.driver = driver
self.locator = locator
@property
def click(self):
return self.driver.find_element_by_xpath(self.locator).click()
class Navigation():
"""NAVIGATION COMMANDS """
def goTo(self):
#somethign
def previousPage(self):
#something
""" BUTTONS """
@property
def view_button(self):
xpath = ".//a[text()='View']"
view = Button(self.driver,xpath)
return view
@property
def create_button(self):
xpath = ".//a[text()='Create']"
create = Button(self.driver,xpath)
return create
在basetestcase.py中:
class BaseTestCase(unittest.TestCase, Navigation)
setUpClass(cls):
#somethign here
并且您的测试用例将采用以下方式:
class TestSomething(BaseTestCase):
def test_99_somethign(self):
#finds .//a[text()='View'] and clicks
self.view.click
#create button
self.create_button.click
这样,您就可以在测试中使用导航类。另外,您可以将所有导航元素保存在一个地方
答案 1 :(得分:1)
我不确定你会怎么做,所以你可以做click.view_button
。但是,您可以为元素提供自己的类。通过这种方式,您可以实现view_button.click()
之类的功能。在我的项目中,我正在为我的所有元素做这件事。
class BaseElement:
def __init__(self, driver, locator):
self.driver = driver
self.locator = locator
def get(self):
self.driver.find_element(locator)
def click():
self.get().click()
class ViewButton(BaseElement):
def __init__(self, driver):
locator = (By.XPATH, ".//a[text()='View']")
super(ViewButton, self).__init__(driver, locator)
class BasePage(object):
def __init__(self, driver):
self.view_button = ViewButton(driver)
class BaseTestCase(unittest.TestCase):
setUpclass(cls):
# driver stuff
self.page = BasePage(driver)
class SomeTest(BaseTestCase):
def test_00_something(self):
self.page.view_button.click()
答案 2 :(得分:1)
感谢RemcoW的帖子我发现了一个解决方案,见下文
class ViewButton():
def __init__(self,driver):
self.driver = driver
self.locator = (".//a[text()='View']")
@property
def click(self):
return self.driver.find_element_by_xpath(self.locator).click()
class BaseTestCase(unittest.TestCase):
#some code here
@property
def view(self):
view = ViewButton(self.driver)
return view
在测试用例中它的工作原理如下
class TestThign(BaseTestCase):
def test_00_something(self):
self.view.click