我已经开始使用Python Selenium并编写了如下所示的脚本。你知道吗
这将打印一个链接到失败测试的返回代码(test01、test02、test03等等)。你知道吗
忽略每个测试都在检查相同的东西。你知道吗
我只是想了解是否有更干净的方法来编写测试,因为每个测试都重复声明global res
,然后有一个try/except
块。你知道吗
有谁能就如何改进这一点提出一些建议吗?你知道吗
# global variable for return code. Zero is success.
res=0
@atexit.register
def send_health():
print ("res=%s") % res
class Login(unittest2.TestCase):
@classmethod
def setUpClass(inst):
binary = FirefoxBinary('C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe')
inst.driver = webdriver.Firefox(firefox_binary=binary)
inst.base_url = "https://stackoverflow.com"
def test01(self):
global res
driver = self.driver
try:
self.assertEqual("Ask a Question", driver.title)
except Exception,e:
print ("Exception: %s" % e)
driver.save_screenshot('screenshot_test01.png')
res=1
return
def test02(self):
global res
driver = self.driver
try:
self.assertEqual("Ask a Question", driver.title)
except Exception,e:
print ("Exception: %s" % e)
driver.save_screenshot('screenshot_test02.png')
res=2
return
def test03(self):
global res
driver = self.driver
try:
self.assertEqual("Ask a Question", driver.title)
except Exception,e:
print ("Exception: %s" % e)
driver.save_screenshot('screenshot_test03.png')
res=3
return
if __name__ == "__main__":
unittest2.main()
这里根本不需要全局变量。您在一个类中;在整个过程中使用
self.res
。你知道吗谢谢你的提示。我已经将代码简化为这个版本,希望它看起来更干净、更标准:
这正是
setUp
实例方法的用途,非常类似于每个测试类运行一次的setUpClass
方法。你知道吗顺便问一下,为什么要使用全局变量?不需要他们。事实上,使用globals很少有一个有效的理由。此外,测试需要独立和独立,使用全局变量将违反这一规则。你知道吗
相关问题 更多 >
编程相关推荐