使用相同的浏览器会话进行Selenium Pytest的多次测试

时间:2016-07-22 12:01:15

标签: python selenium

我希望能够在同一个测试文件中使用相同的浏览器会话进行多次测试。

我为登录设置了一个班级:

class Loginpage ():
 url="http://appsv01:8084/#/"

 def __init__(self, workbook):
    self.workbook=workbook

 def login(self,value_Name,worksheet):
    #Open a new mymobile suite window in Chrome and maximize
    driver = webdriver.Chrome('C:/temp/chromedriver.exe')
    driver.get("http://appsv01:8084")
    driver.maximize_window()

我一直关闭浏览器会话,然后每次测试打开一个新会话,但我尝试更改它以便结构看起来像(在名为test_mytests.py的文件中):

   #open the browser and log in
   mylogin=Loginpage('C:\Automation\Common_Objects.xlsx')
   driver=mylogin.login("AutoSMS", "Users")

   #perform the first test
   def test_one():
    task1
    task2

   #perform the second test
    def test_two():
    task3
    task4

失败并显示错误:

E   ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it

如果我将#open的代码分别放在每个测试的浏览器下,那么一切正常。是否可以只打开一次浏览器并让文件中的所有测试都在同一个浏览器会话上工作?

1 个答案:

答案 0 :(得分:0)

您可以将驱动程序对象传递给函数调用:

 #open the browser
 driver = webdriver.Chrome('C:/temp/chromedriver.exe')
 driver.get("http://appsv01:8084")
 driver.maximize_window()

 #perform the first test
 def test_one(driver):
  #do something with driver here, e.g.
  driver.find_element_by_id('test').click()


 #perform the second test
 def test_two(driver):
   task3
   task4

 #function calls
 test_one(driver)
 test_two(driver)

 #close driver
 driver.close()