Python webdriver:重用setUp和tearDown

时间:2015-12-05 15:50:37

标签: python oop automation webdriver

您好,我可以举例说明在另一个类中重用setUp和tearDown,例如

base.py

from selenium import webdriver
class Login(object):
  def setUp(self):
  # create a new Firefox session
   self.driver = webdriver.Firefox()
   self.driver.get("google.com")
   self.driver.implicitly_wait(30)
   self.driver.maximize_window()

  def tearDown(self):
    self.driver.quit()

login.py

from selenium import webdriver
import base
import unittest

class LoginPage(unittest.TestCase):
 ...how to call setUp() and tearDown() from base.py...
    def test_logn(self):
        self.driver.find_element_by_id('username')
     ...etc...

您能提供示例请在PC上运行并查看其工作原理。谢谢

1 个答案:

答案 0 :(得分:2)

LoginPage设为base.Login的子类,以便它继承Login.setUpLogin.tearDown

base.py

import unittest
from selenium import webdriver

class Login(unittest.TestCase):

    def setUp(self):
        # create a new Firefox session
        self.driver = webdriver.Firefox()
        self.driver.get("http://google.com")
        self.driver.implicitly_wait(30)
        self.driver.maximize_window()

    def tearDown(self):
        self.driver.quit()

login.py

from selenium import webdriver
import base
import unittest

class LoginPage(base.Login):

    def test_logn(self):
        elt = self.driver.find_element_by_name('q')
        elt.send_keys('python')
        elt.submit()
        for result in self.driver.find_elements_by_class_name('g'):
            print(result.text)
            print('-' * 80)

if __name__ == '__main__':
    unittest.main()