| Version 1 (modified by chenyang, 12 years ago) (diff) |
|---|
如何测试异步实现的功能
7.0论坛的发帖功能使用ajax异步提交请求,为了验证发帖,我们需要在发帖后,让当前线程睡眠N秒,等待发帖完成,如下:
......
#点击发帖按钮
driver.find_element_by_css_selector("div.fatie_action > a > img").click()
#当前线程睡眠10秒,等待发帖完成
time.sleep(10)
#断言帖子标题
self.assertNotEqual(-1,driver.title.find(title))
......
这里有一个问题,10秒,是一个漫长的等待过程,但如果设置1秒呢,发帖并不一定能完成,接下来的断言会失败,而且,10秒只是一个我们估算出来的
在大多数情况下,完成发帖所花费的时间。有时,可能10秒也不够,那么发帖到底需要多少时间呢?我们可以开发函数来监控
def sleep_until_done(fun, timeout = 30): u''' 检查指定的条件是否成熟, 若未成熟则继续sleep,直到超时 ''' for v in range(0, timeout): if fun(): return True else: time.sleep(1) return False
我们知道如果发帖成功,那么浏览器会重定向到帖子页.利用这个检查方法, 现在我们开发条件函数
def is_topic_page(self): u''' 是否是帖子页 ''' driver = self.driver topic_url = driver.current_url regex = self.base_url + "/topic-" + "\d+\.html" match = re.match(regex, topic_url) return match is not None
现在,我们来优化一下,发帖的过程
......
#点击发帖按钮
driver.find_element_by_css_selector("div.fatie_action > a > img").click()
#当前线程休眠,完成发帖过程
functions.sleep_until_done(self.is_topic_page)
#断言帖子标题
self.assertNotEqual(-1,driver.title.find(title))
......
![(please configure the [header_logo] section in trac.ini)](http://www1.pconline.com.cn/hr/2009/global/images/logo.gif)