python selenium 同一个页面两个case中,driver 如何在unittest 中传递

测试一个登录登出,我在登录时已经实例化一个webdriver,我想在登出的case中引用这个driver.怎么样才能引用到该driver?

为什么我要引用登录case中的driver,而不是在登出case中再实例化一个driver? 如果我在登出时再次实例化一个driver, 那么就要再打开一个浏览器并且要给定一个url,显得测试不连续;

代码如下所示


class TestLogin(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Chrome()
        self.driver.implicitly_wait(10)
        self.driver.get('https://www.some.com/aa/login.jsp')

    def test_login(self):
        username = 'xxx'
        password = 'yyy!'

        login_page = Login()
        login_page.user_login(self.driver, username, password)

        self.check_login()

    def check_login(self):
        current_url = self.driver.current_url
        expected_url = '/aa/main/index.do'
        self.assertIn(expected_url, current_url, msg="登录失败")

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

class TestLogout(unittest.TestCase):
    # 往往登录后case依赖于登录case
    def setUp(self, driver):
        self.driver = driver

    def test_logout(self):
        logout_button = self.driver.find_element_by_xpath("//a[@onclick='exitLogin();']")
        logout_button.click()

        logout_confirm = self.driver.find_element_by_css_selector(".exitLogin .btn-primary")
        logout_confirm.click()

        self.check_logout()

    def check_logout(self):
        current_url = self.driver.current_url
        expected_url = 'aa/login.jsp'
        self.assertIn(expected_url, current_url, msg="登出失败")

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


if __name__ == '__main__':
    suite = unittest.TestSuite()
    suite.addTest(TestLogin("test_login"))
    suite.addTest(TestLogout("test_logout"))

    runner = unittest.TextTestRunner()
    runner.run(suite)
阅读 3.2k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进