【问题标题】:Python Selenium: How to reuse a class from another classPython Selenium:如何重用另一个类中的一个类
【发布时间】:2018-03-14 22:36:20
【问题描述】:

我是 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)

【问题讨论】:

  • 你能修正你的代码格式吗?
  • 修复了我的示例代码中的缩进问题
  • self.driver.find_element_by_xpath("".//*[@id='aoTkt']/div/div")).click() 中,你有 "("...."))".().. 这意味着你的代码中有太多的 ")" 括号。错字?
  • 是的,额外的)这是一个错字。但问题是如何使用从一个类调用的浏览器来继续下一个测试用例,它是在另一个类中编写的。

标签: python selenium


【解决方案1】:

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

from mylogin import myLoginclass

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

Unittest setUp/tearDown for several tests

【讨论】:

  • 此解决方案部分有效。 myorder 类运行,其中包括 myloginclass,后跟 myorder 类。但在此之后,myloginclass 再次执行,打开一个新的浏览器并登录。
猜你喜欢
  • 2020-11-27
  • 1970-01-01
  • 1970-01-01
  • 2015-12-19
  • 1970-01-01
  • 1970-01-01
  • 2011-07-03
  • 2018-11-05
  • 1970-01-01
相关资源
最近更新 更多