多线程执行测试用例
这里以百度搜索为例,通过不同的浏览器来启动不同的线程。
1 #!/usr/bin/env python 2 # _*_ coding:utf-8 _*_ 3 __author__ = ‘YinJia‘ 4 5 from threading import Thread 6 from selenium import webdriver 7 from time import ctime,sleep 8 9 #测试用例 10 def test_baidu(browser,search): 11 print(‘start: {0}‘.format(ctime())) 12 print(‘browser: {0}‘.format(browser)) 13 if browser == "ie": 14 driver = webdriver.Ie() 15 elif browser == "chrome": 16 driver = webdriver.Chrome() 17 elif browser == "ff": 18 driver = webdriver.Firefox() 19 else: 20 print("browser参数有误,只能为 ie、ff、chrome") 21 22 driver.get("http://www.baidu.com") 23 driver.find_element_by_id("kw").send_keys(search) 24 driver.find_element_by_id("su").click() 25 sleep(2) 26 driver.quit() 27 28 if __name__=="__main__": 29 lists = {‘chrome‘:‘C++‘,‘ie‘:‘JAVA‘,‘ff‘:‘python‘} 30 threads = [] 31 files = range(len(lists)) 32 33 #创建线程 34 for browser,search in lists.items(): 35 t = Thread(target=test_baidu,args=(browser,search)) 36 threads.append(t) 37 #启动线程 38 for t in files: 39 threads[t].start() 40 for t in files: 41 threads[t].join() 42 print(‘end: {0}‘.format(ctime())) 43 44 运行结果: 45 start: Mon Aug 20 00:09:50 2018 46 browser: chrome 47 start: Mon Aug 20 00:09:50 2018 48 browser: ie 49 start: Mon Aug 20 00:09:50 2018 50 browser: ff 51 end: Mon Aug 20 00:10:09 2018
可见同时运行三个不同的浏览器环境执行测试用例。
多线程分布式执行测试用例
Selenium Grid本身不提供并发执行用例,只是提供多系统、多浏览器执行环境,鉴于并发执行需要用到多线程技术结合Grid来实现分布式并发执行测试用例。
在一台主机上启动一个hub主节点和一个node分支节点,另一台主机启动一个node分支节点如下所示:
- 启动本机hub主机:java -jar selenium-server-standalone-2.53.0.jar -role hub [默认4444端口]
- 启动本机node分支节点:java -jar selenium-server-standalone-2.53.0.jar -role node -port 5555
- 在远程主机启动node分支节点:java -jar selenium-server-standalone-2.53.0.jar -role node -port 6666 -hub http://192.168.31.210:4444/grid/register
1 #!/usr/bin/env python 2 # _*_ coding:utf-8 _*_ 3 __author__ = ‘YinJia‘ 4 5 6 from threading import Thread 7 from selenium import webdriver 8 from time import ctime,sleep 9 10 #测试用例 11 def test_baidu(host,browser): 12 print(‘start:{0}‘.format(ctime())) 13 print(host,browser) 14 dc = {‘browserName‘:browser} 15 driver = webdriver.Remote(command_executor=host, 16 desired_capabilities=dc) 17 driver.get("http://www.baidu.com") 18 driver.find_element_by_id("kw").send_keys(browser) 19 driver.find_element_by_id("su").click() 20 sleep(2) 21 driver.quit() 22 23 if __name__=="__main__": 24 #启动参数(指定运行主机与浏览器) 25 lists = {‘http://127.0.0.1:4444/wd/hub‘:‘chrome‘, 26 ‘http://192.168.31.230:6666/wd/hub‘: ‘internet explorer‘, 27 ‘http://1127.0.0.1:5555/wd/hub‘: ‘firefox‘} 28 threads = [] 29 files = range(len(lists)) 30 31 #创建线程 32 for browser,search in lists.items(): 33 t = Thread(target=test_baidu,args=(browser,search)) 34 threads.append(t) 35 #启动线程 36 for t in files: 37 threads[t].start() 38 for t in files: 39 threads[t].join() 40 print(‘end: {0}‘.format(ctime()))
原文地址:https://www.cnblogs.com/yinjia/p/9503397.html
时间: 2024-10-10 21:25:15