第二步, 根据每个testcase建立TestCase类的实例:
class TestCase:
def __init__(self, _testcase):
self.name=_testcase.attrib['name']
_list=[]
self.actions=[]
try:
_list=_testcase.getchildren()
except Exception,msg:
print msg
self._executor=_testcase.find('Executable').text
self.address=_testcase.find('Address').text
for act in _testcase.findall('Action'):
if act.tag=='Action':
_action=Action(act)
self.actions.append(_action)
def setUp(self):
if 'Chrome'==self._executor:
self.executor=webdriver.Chrome()
elif 'Firefox'==self._executor:
self.executor=webdriver.Firefox()
else:
self.executor=webdriver.Ie()
self.executor.get(self.address)
def tearDown(self):
self.executor.quit()
def execute(self):
logging.debug("Start to execute the testcase:%s" % self.name)
print "TestCaseName:%s" % self.name
try:
self.setUp()
for action in self.actions:
action.execute(self.executor);
self.tearDown()
Assert.AssertPass("TestCase:%s " % self.name)
except Exception as error:
print error
self.tearDown()
Assert.AssertFail("TestCase:%s " % self.name)
第三步,根据xml里定义的type来触发动作,我简单的列了下:
def execute(self,executor):
_type=self._actions['Type']
self.getBy(self._actions)
try:
if self.by!=None:
ele=self.findElement(executor)
Assert.AssertIsNotNull(ele," ".join("Find element by %s:%s" % (str(self.by),self.by_value)))
if _type=='Input':
ele.send_keys(self._actions['Content'])
time.sleep(3)
elif _type=='Click':
ele.click()
elif _type=='Scroll':
webOperate.page_scroll(executor)
elif _type=='Back':
webOperate.goBack(executor)
else:
print " ",
Assert.AssertFail(self._name)
print "No such action:%s" % _type
if self._expected is not None:
Assert.AssertIsTrue(self.isExpected(executor)," ".join("Find element by %s:%s" % (str(self.by),self.by_value)))
print " ",
Assert.AssertPass(self._name)
except AssertionError:
print " ",
Assert.AssertFail(self._name)
raise AssertionError(self._name +" execute failed")
看一个运行的截图
代码比较简单,原理也很清晰,是解析XML文件,然后调用相应的selenium代码,但是如果我们再深入的想想,在解析这些XML的时候,是不是可以以更友好的方式来展示生成的代码呢,甚或者以UI的方式,一条条展示。然后再提供可编辑功能?甚或者再提供录制的方式来自动生成这些XML文件,再解析成代码,这不是一个强大的自动化测试工具??