如果我有多个类,如类Page,类Page1,类Page2需要使用相同的Element类。为了在ELement类上使用self.driver,我需要在每个class Ele(e)
上复制从class itemWrap
到class Page
的大量代码,以传递self.driver
作为输入。构建以下代码的最佳方法是什么?
# elements.py
class Element(object):
def addItem(self, owner=None):
for _i in owner:
options = self.findAvaItem()
i = options.index(_i)
self.ele.find_element_by_xpath('{}/{}'.format(self.l, i)).click()
def delItem(self, owner=None):
for _i in owner:
options = self.findSelecItem()
i = options.index(_i)
self.ele.find_element_by_xpath('{}/{}'.format(self.l, i)).click()
def findAvaItem(self):
_o = self.driver.find_element_by_css_selector('css==div.menu.transition.visible').text
return _o.split('\n')
def findSelecItem(self):
_o = self.driver.find_element_by_css_selector('css==a.ui.label')
return [i.text for i in _o]
# BasePage.py
class BasePage(object):
def __init__(self, driver):
self.driver = driver
# Page.py
from elements import Element as e
class Ele(e):
def __init__(self, driver, _t):
self.driver = driver
self.l = 'element l variable'
self.t = _t
class itemWrap(object):
def __init__(self, driver, _type):
self.ele = Ele(driver, _type)
self.driver = driver
self.t = _type
def sel_item(self, _value):
self.ele.addItem(_value)
def desel_item(self, _value):
self.ele.delItem(_value)
class Page(BasePage):
def inputItem(self, _type, _value):
itemWrap(self.driver, _type).sel_item(_value)
def removeItem(self, _type, _value):
itemWrap(self.driver, _type).desel_item(_value)
# Test.py
from Page import Page
from selenium import webdriver as WebDriver
class Test(object):
@classmethod
def setup_class(cls):
if hasattr(super(Test, cls), 'setup_class'):
super(Test, cls).setup_class()
cls.driver = WebDriver(desired_capabilities=chrome, command_executor='127.0.0.1')
def check_function(self):
self.Page.inputItem('typeA', ['item A1', 'item A2', 'item A3'])
self.Page.removeItem('typeA', ['item A1', 'item A2', 'item A3'])
self.Page.inputItem('typeB', ['item B1', 'item B2'])
self.Page.removeItem('typeB', ['item B1', 'item B2'])
答案 0 :(得分:1)
您似乎正在尝试在itemWrap
课程中构建一个外观图层,以便itemWrap
的每个方法都只是调用self.ele
。这是对的吗?
如果是这样,您可以动态生成功能。 (如果在wrap-method和element-method名称中存在一致的文本模式,则可以执行更多自动化操作。因此,您必须提供dict。)
class Ele:
def addItem(self, x):
print("Additem",x)
def delItem(self, x):
print("DelItem",x)
class ItemWrap:
def __init__(self, ele):
self.ele = ele
method_map = {
'sel_item': 'addItem',
'desel_item': 'delItem',
# more methods go here
}
for myname, elname in ItemWrap.method_map.items():
msrc = "def {}(self, _value):\n" \
" return self.ele.{}(_value)\n".format(myname, elname)
gbls = {}
exec(msrc, gbls)
setattr(ItemWrap, myname, gbls[myname])
e = Ele()
i = ItemWrap(e)
i.sel_item(10)
i.desel_item(11)