Python Selenium:如何重用另一个类中的类

时间:2018-03-14 22:36:20

标签: python selenium

我是Python和selenium的新手。我需要编写一个可以在我的测试用例中重用的登录模块。这是我的2个文件。我需要帮助来调用登录模块,以便浏览器启动并且用户可以登录。然后第二个模块启动并开始测试用例(在同一个浏览器中)。我在2个单独的文件中写了2个类。我的代码如下:

mylogin.py文件

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.common.exceptions import NoSuchElementException
import unittest
class myLoginclass(unittest.TestCase):
    @classmethod   
    def test_TC_1_login_page(self):       
        self.driver = webdriver.Firefox()
        self.driver.get(http://www.gmail.com)
        self.driver.find_element_by_xpath(".//*[@id='name-group']/input").send_keys("HELLO")
        self.driver.find_element_by_xpath(".//*[@id='password-group']/input").send_keys("WORLD")
        self.driver.find_element_by_id("loginButton").click()

if __name__ == '__main__':
    unittest.main(failfast=True, exit=False)

myorder.py文件:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.common.exceptions import NoSuchElementException
import unittest
from mylogin import myLoginclass
class myorderclass(unittest.TestCase):
    @classmethod   
    def test_TC_2_orderProcess(self):       
        self.driver.find_element_by_xpath("".//*[@id='aoTkt']/div/div")).click()
        self.driver.find_element_by_xpath(".//*[@id='presales']/input").click()
        self.driver.find_element_by_link_text("DISPATCH").click()
        self.driver.find_element_by_id("submitButton").click()

if __name__ == '__main__':
    unittest.main(failfast=True, exit=False)

1 个答案:

答案 0 :(得分:0)

使用类继承。根据您的使用情况,使用setUp()或setUpClass()调用登录函数。

from mylogin import myLoginclass

class myorderclass(myLoginclass):
    def setUp(self):
        self.test_TC_1_login_page()

Unittest setUp/tearDown for several tests